【问题标题】:Cython Pass String To C as BytesCython 将字符串作为字节传递给 C
【发布时间】:2017-02-08 06:55:18
【问题描述】:

我需要在 python 中构建一个字符串并将其传递给包装好的 C 库。 C库定义了函数:

unsigned char load(char const *FileName)

在 .pyx 文件中:

def test():
    PATH = '/usr/lib/libnx.so'
    PATH = <char*>PATH
    load(PATH)

但我得到:TypeError: expected bytes, str found

我尝试过对 python 字符串进行编码,但得到了同样的错误。

【问题讨论】:

  • .encode() 应该可以解决这个问题

标签: python c cython


【解决方案1】:

在 Python 中,str 对象不是 C 中的字节数组。为此,您必须对字符串进行编码。默认为 UTF-8 编码,向后兼容 ASCII。

这里有两种传递字节数组的方法:

  • 选项 1:从一开始就将 PATH 定义为 bytes 对象:
    • PATH = b'/usr/lib/libnx.so',或:
    • PATH = 'usr/lib/libnx.so'.encode()
  • 选项 2:在传递 PATH 时将其编码为字节数组:
    • load(PATH.encode())

【讨论】:

  • 很奇怪,我无法复制。你可能忘记重建了吗?我使用了cpython 并导入了stdlib::atoi(),它在参数中也使用了char const *。当我通过 str 对象时,它失败了(就像你的一样),但是在使用 .encode() 之后它起作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 2011-11-26
  • 1970-01-01
  • 2023-03-15
  • 2020-05-28
相关资源
最近更新 更多