ctypes结构字段中的固定大小char数组和初始化

时间:2019-01-19 02:28:23

标签: arrays python-3.x ctypes

如何使用char a[32]初始化结构的字段的固定大小的字符数组,例如ctypes?示例:

import ctypes

class MyStructure(ctypes.Structure):
    _fields_ = [("a", ctypes.c_char * 32)]

a = (ctypes.c_char * 32)(*b"Hi!")
mystruct = MyStructure(a=a)

这给了我一个错误:

Traceback (most recent call last):
  File "...", line ..., in <module>
    mystruct = MyStructure(a=a)
TypeError: expected bytes, c_char_Array_32 found

其他信息:这是C ++ DLL的MWE,其结构具有固定大小的字符数组,这些字符串用作字符串(例如事物名称)。

1 个答案:

答案 0 :(得分:1)

按照错误消息的提示传递字节字符串。如果时间太长,ctypes会抱怨:

import ctypes

class MyStructure(ctypes.Structure):
    _fields_ = [("a", ctypes.c_char * 32)]

mystruct = MyStructure(b'Hi')
print(mystruct.a)
mystruct = MyStructure(b'Hi'*16)
print(mystruct.a)
mystruct = MyStructure(b'Hi'*17)
print(mystruct.a)

结果:

b'Hi'
b'HiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHi'
Traceback (most recent call last):
  File "D:\dev\Python36\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
    exec(codeObject, __main__.__dict__)
  File "C:\Users\metolone\Desktop\x.py", line 10, in <module>
    mystruct = MyStructure(b'Hi'*17)
ValueError: bytes too long (34, maximum length 32)