Saving XML as ctypes c_byte in variable gives TypeError: an integer is required

Saving XML as ctypes c_byte in variable gives TypeError: an integer is required

在 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

我该如何解决这个问题。谢谢!

A c_byte 数组将可变数量的 int 作为参数,您正试图给它一个列表。试试这个:

xml_bytes = bytearray(b'<xml>...')
XMLparamsVal = (ctypes.c_byte*2049)(*xml_bytes)

*xml_bytes 扩展为一系列位置 int 参数。

对于python3,你不需要bytearray,你可以直接使用字节字面量,如python3迭代一个byte对象产生ints :

XMLparamsVal = (ctypes.c_byte*2049)(*b'<xml>...')

请注意,对于 A class 的第一个参数,您还必须传递 c_byte_Array_41,而不是字符串。