python - 将 XML 保存为变量中的 ctypes c_byte 会给出 TypeError : an integer is required

标签 python c xml ctypes

在 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 对象产生 ints:

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/

相关文章:

python - 为什么当我过滤时 Django Rest Framework 在我的 URL 上添加斜杠?

c - 不兼容的指针类型错误 C

python - 如何对数据集表中的列索引进行标签编码?

python - Python 3 中单元测试的预设输入

python - odoo 中 many2one 字段的域过滤器?

java - 如何获取 XML 中特定标签的列表

java - 文档根元素 "beans",必须匹配 DOCTYPE 根 "null"

c - 在子进程C程序中存储数据

c++ - 基准测试代码——我做的对吗?

c++ - Xerces C++ Unresolved 链接器错误