我正在尝试使用 ctypes 来控制仪器(相机)。我想知道如果我调用的 C 函数期望 char *pList
作为参数,我应该在 ctypes 中做什么。 .h 头文件中的文档是:
////////////////////////////////////////////////////////////////////////////////
/// Opening the camera
////////////////////////////////////////////////////////////////////////////////
/// Enumerates all available devices. Device names are separated by a pipe '|' symbol.
/// @param pList zero terminated string which will receive the device list
/// @param iMaxLen allocated memory available for the device list
/// @return A device list containing 'connectionurl'|'description' ..
static void IMPEXP GetDeviceList(char *pList, int iMaxLen);
我试过类似的方法:
data = ctypes.c_char_p(64)
lib.XC_GetDeviceList(ctypes.pointer(data),64)
但它似乎没有正确执行(返回值不为零)。我需要提供的正确输入参数是什么?
最佳答案
create_string_buffer
创建 DLL 可以写入的缓冲区。使用 .value
和 .raw
访问内容:
>>> data = ctypes.create_string_buffer(5)
>>> data
<ctypes.c_char_Array_5 object at 0x000001D142F2D948>
>>> data.raw
b'\x00\x00\x00\x00\x00'
>>> data.value
b''
.raw
列出缓冲区中的所有字节。
.value
返回直到终止 null 的数据。
这是一个例子:
from ctypes import *
dll = CDLL('camera') # Use your DLL name
# Not always required, but allows ctypes to better error check the call.
dll.GetDeviceList.argtypes = c_char_p,c_int # argument types
dll.GetDeviceList.restype = None # return type
pList = create_string_buffer(1000) # Create a writable char* buffer.
dll.GetDeviceList(pList,len(pList))
print(pList.value) # Your documentation says null-terminated data is returned.
关于c++ - ctypes 中的 "char *pList",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48684689/