在 C 头文件中我有:
long TEST_API test (
___OUT_ char DisplayText[41],
_IN____ const char XMLparams[2049]
);
在 python 代码中,我导入了 ctypes
并且我正在尝试调用“Test”。
class A(Structure):
_fields_ = [("DisplayText", c_byte*41),
("XMLparams",c_byte*2049)
]
XMLparamsVal = (ctypes.c_byte*2049)(["<xml><MatchboxDataProviderValue>Openvez</MatchboxDataProviderValue><AlwaysPrintTwoTicketsFlag>FALSE</AlwaysPrintTwoTicketsFlag><DisplayWidthInCharacters>20</DisplayWidthInCharacters><!-- exclude Ikea-Card and Maestro from PAN truncation --><DontTruncateList>*119*1*</DontTruncateList></xml>"])
my_A = A("", XMLparamsVal)
lib.test(my_A.DisplayText, my_A.XMLparams)
我遇到了这个错误:
XMLparamsVal = (ctypes.c_byte*2049)(["<xml><MatchboxDataProviderValue>Openvez</MatchboxDataProviderValue><AlwaysPrintTwoTicketsFlag>FALSE</AlwaysPrintTwoTicketsFlag><DisplayWidthInCharacters>20</DisplayWidthInCharacters><!-- exclude Ikea-Card and Maestro from PAN truncation --><DontTruncateList>*119*1*</DontTruncateList></xml>"])
TypeError: an integer is required
我该如何解决这个问题。谢谢!
最佳答案
c_byte
数组将可变数量的 int
作为参数,您正试图给它一个列表。试试这个:
xml_bytes = bytearray(b'<xml>...')
XMLparamsVal = (ctypes.c_byte*2049)(*xml_bytes)
*xml_bytes
被扩展为一系列位置 int
参数。
对于 python3,你不需要 bytearray,你可以直接使用字节字面量,因为在 python3 中迭代一个 byte
对象产生 int
s:
XMLparamsVal = (ctypes.c_byte*2049)(*b'<xml>...')
请注意,对于 A
类的第一个参数,您还必须传递 c_byte_Array_41
,而不是字符串。
关于python - 将 XML 保存为变量中的 ctypes c_byte 会给出 TypeError : an integer is required,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28141317/