【问题标题】:Define array length for c_char Python为 c_char Python 定义数组长度
【发布时间】:2015-02-01 23:10:04
【问题描述】:
在 C 头文件中我有:
long param_API test(
___OUT_ char Text[41]
)
在 Python 代码中导入 ctypes 后,我正在调用 test:
out_char = (ctypes.c_char)()
def getRes():
result = lib.test(out_char)
return result
但我会在日志文件中收到此错误:
output parameter is NULL
我想测试函数没有足够的空间来写入你的输出。我在这里做错了什么?如何设置out_char 的长度?
【问题讨论】:
标签:
python
c
compilation
header
ctypes
【解决方案1】:
要创建数组,请使用:
out_char = (ctypes.c_char * 41)()
这会创建一个数组对象的实例:
>>> (ctypes.c_char*41)()
<__main__.c_char_Array_41 object at 0x0000000002891048>
您可以访问各个元素:
>>> out_char[0]
b'\x00'
>>> out_char[40]
b'\x00'
>>> out_char[41]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index
对于c_char,整个缓冲区:
>>> out_char.raw
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
或者只是以 nul 结尾的部分:
>>> out_char.value
b''