Python 3.5, ctypes: TypeError: bytes or integer address expected instead of str instance

Python 3.5, ctypes: TypeError: bytes or integer address expected instead of str instance

我遇到了 ctypes 的问题。我认为我的类型转换是正确的,错误对我来说没有意义。 “arg - ct.c_char_p(logfilepath)”行出错 类型错误:需要字节或整数地址而不是 str 实例

我在 python 3.5 和 3.4 中都试过了。

我调用的函数:

stream_initialize('stream_log.txt')

Stream_initialize代码

def stream_initialize(logfilepath):
    f = shim.stream_initialize
    arg = ct.c_char_p(logfilepath)
    result = f(arg)

    if result:
        print(find_shim_error(result))

c_char_p 接受 bytes 对象,因此您必须先将 string 转换为 bytes

ct.c_char_p(logfilepath.encode('utf-8'))

另一种解决方案是使用 c_wchar_p 类型,它采用 string.

为了完整起见: 也可以称其为stream_initialize(b'stream_log.txt')。请注意字符串前面的 b,这会导致它被解释为 bytes 对象。