python callable wrapping c callable with c_char_p argtype 的奇怪 ctypes 行为

Strange ctypes behaviour on python callable wrapping c callable with c_char_p argtype

我在以下测试程序中观察到一个奇怪的 ctypes 相关行为:

import ctypes as ct

def _pyfunc(a_c_string):
    print(type(a_c_string))
    a_c_string.value = b"87654321"
    return -123

my_str_buf = ct.create_string_buffer(b"test1234")
print(type(my_str_buf))

my_str_buf[3] = b'*'
print(my_str_buf.value)

my_str_buf.value = b"4321test"
print(my_str_buf.value)

signature = ct.CFUNCTYPE(ct.c_int, ct.c_char_p)
pyfunc = signature(_pyfunc)
pyfunc(my_str_buf)
print(my_str_buf.value)

该示例通过 ctypes api 在 python 函数中包装了一个 python c 可调用函数。 目标是向 python 函数传递一个指向 c 字符串的指针,让它修改它的内容(提供一个假值),然后 return 给调用者。

我首先通过 ctypes 函数 create_string_buffer 创建了一个可变字符串缓冲区。 从示例中可以看出,字符串缓冲区确实是可变的。

之后,我使用 ctypes.CFUNCTYPE(ct.c_int, ct.c_char_p) 创建了一个 c 函数原型,然后使用我的 python 函数实例化了该原型,该函数应该使用相同的签名来调用。最后,我用我的可变字符串缓冲区调用 python 函数。

令我恼火的是,当调用该函数时,传递给该函数形状的参数从 <class 'ctypes.c_char_Array_9'> 类型转变为 <class 'bytes'> 类型。不幸的是,原始的可变数据类型变成了完全无用的非可变字节对象。

这是 ctypes 错误吗? Python 版本是 3.6.6.

这是输出:

<class 'ctypes.c_char_Array_9'>
b'tes*1234'
b'4321test'
<class 'bytes'>
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 234, in 'calling callback function'
  File "C:/Users/andree/source/Python_Tests/ctypes_cchar_prototype.py", line 5, in _pyfunc
    a_c_string.value = b"87654321"
AttributeError: 'bytes' object has no attribute 'value'
b'4321test'

预期输出:

<class 'ctypes.c_char_Array_9'>
b'tes*1234'
b'4321test'
<class 'ctypes.c_char_Array_9'>
b'87654321'

ctypes.c_char_p自动转换为Pythonbytes。如果您不想要这种行为,请使用:

  • ctypes.POINTER(ctypes.c_char))
  • class PCHAR(ctypes.c_char_p): pass(推导抑制行为)

请注意 LP_c_char 没有 .value 属性,因此我不得不直接取消引用指针以影响值的变化。

此外,注意不要超过传入的可变缓冲区的长度。我添加了 length 作为附加参数。

示例:

import ctypes as ct

@ct.CFUNCTYPE(ct.c_int, ct.POINTER(ct.c_char), ct.c_size_t)
def pyfunc(a_c_string,length):
    new_data = b'87654321\x00' # ensure new null termination is present.
    if len(new_data) > length: # ensure new data doesn't exceed buffer length
        return 0 # fail
    for i,c in enumerate(new_data):
        a_c_string[i] = c
    return 1 # pass

my_str_buf = ct.create_string_buffer(10)
result = pyfunc(my_str_buf,len(my_str_buf))
print(result,my_str_buf.value)

my_str_buf = ct.create_string_buffer(8)
result = pyfunc(my_str_buf,len(my_str_buf))
print(result,my_str_buf.value)
1 b'87654321'
0 b''