c++ - ctypes 中的 "char *pList"

标签 c++ string python-3.x pointers ctypes

我正在尝试使用 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/

相关文章:

c++ - 使用 C++11 将我的比较函数传递给 std::multiset

python - 为 Python 3 安装 pip

c++ - Qt Designer(创建者)小部件框,如小部件

c++ - Visual C++ 2012 和 PCRE

c# - 在 C# 中编辑字符串中的字符

string -++ 运算符与字符串和 IO 字符串

python - input() - 行继续符后的意外字符

python - 重写 __eq__ 并比较两个对象

python - _event.cpython-310-x86_64-linux-gnu.so : undefined symbol: _PyGen_Send 导入错误

c++ - (C++) 将指针传递到模板中