【发布时间】:2019-01-08 10:03:51
【问题描述】:
我有一个共享 C 库,其中包含一个我想在我的 python 代码中使用的结构
struct my_struct {
char name[64];
};
所以在 python 中我重新创建它
class MyStruct(ctypes.Structure):
_fields_ = [
("name", ctypes.c_char*64)
]
当我检查 MyStruct.name 的类型时,我得到 'str',而我期望的是 'c_char_Array_64'。
s=MyStruct()
print type(s.name) # <type 'str'>
所以当我设置“名称”并尝试使用它时,C 将其视为空白。
s.name="Martin"
lib=ctypes.cdll.LoadLibrary('./mylib.so')
lib.my_func(s) # prints ''
其中 lib 是加载了 ctypes 的共享 C 库,而 my_func 只是打印 struct->name
void my_func(struct my_struct *s){
printf("Hello %s\n", s->name);
}
我想知道为什么ctypes.Structure将char-array转换为字符串以及如何在上面指定的情况下使用它。
谢谢
更新与解决方案
感谢@CristiFati 帮助调试此问题。我已将他的答案标记为正确,因为它实际上是已发布问题的答案。在我的情况下,问题是 Python 和 C 程序中的结构不是 等长。因此,对于将来偶然发现这个问题的人,请非常仔细地检查您的结构实际上是否被平等地定义。
【问题讨论】:
-
你能说明 my_func 是如何在 C 中定义并包装在 ctypes/python 中的吗?
-
上面已经显示了
-
您需要在 Python (
lib.my_func.argtypes = [ctypes.POINTER(MyStruct)]) 中为您的函数定义 argtypes(和 restype),然后调用它:lib.my_func(ctypes.pointer(s)))。大多数 ctypes 失败都是由于这个原因。查看stackoverflow.com/questions/53182796/…(以及大量其他问题)了解更多详情。 -
谢谢@CristiFati,我会试试这个
-
对不起@CristiFati,s->名字还是空白。还有什么我可以尝试的其他方法吗?
标签: python arrays string ctypes