python - 使用 ctypes 在 Python 中读取 C 结构

标签 python c ctypes

我在 Python3 中使用 ctypes 调用外部函数。

C 函数应该返回指向结构的指针:

struct sLinkedList {
    void* data;
    struct sLinkedList* next;
 };

typedef struct sLinkedList* LinkedList;

在C中定义的函数如下。

LinkedList IedConnection_getServerDirectory (IedConnection  self, IedClientError *  error, bool     getFileNames )  

所以我的 Python3 代码如下:

from ctypes import *

...

class LinkedList(Structure):
    pass

LinkedList._fields_ = [("data",c_void_p), ("next",  POINTER(LinkedList))]

...

IedConnection_getServerDirectory=dlllib.IedConnection_getServerDirectory
IedConnection_getServerDirectory.argtypes=[c_void_p, c_void_p]
IedConnection_getServerDirectory.restype = c_int
LogicalDevicesPtr = IedConnection_getServerDirectory(IedConnection,iedClientError)

IedConnection 参数由其他函数作为指针检索,我很确定它工作正常。我还可以看到该功能本身运行良好(它启动通信,可以在 Wireshark 中看到)。

然后我尝试获取函数结果的信息:

LogicalDevicesList_p = cast(LogicalDevicesPtr,POINTER(LinkedList))

LogicalDeviceList = LogicalDevicesList_p.contents

这一行通过,下面一行失败:

Rdata = LogicalDeviceList.data

带有“段错误:11”

我想问题出在类型定义上,但我不知道错误出在哪里。谁能帮忙?

最佳答案

嗯,看来我自己解决了:

IedConnection_getServerDirectory.restype = c_int

不正确,应更改为:

IedConnection_getServerDirectory.restype = c_void_p

它已经开始正常工作了。

但另外我在函数调用中添加了第三个参数以使其更简洁:

IedConnection_getServerDirectory.argtypes=[c_void_p, c_void_p, c_bool]
LogicalDevicesPtr = IedConnection_getServerDirectory(IedConnection,iedClientError,c_bool(False))

关于python - 使用 ctypes 在 Python 中读取 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38959713/

相关文章:

python - 使用 ctypes : undefined symbol 将 C++ 函数导出到 python

python - cx_卡住/ldap : ImportError: DLL Load Failed %1 is not a valid Win32 application

python - 使用 python 和 cocoa 设置 : OS X 10. 6.6 + XCode3.2

C++ 将对象创建为静态 - 需要关于良好实践的建议

c - 三元运算符的替代

python - 是否有在 cygwin 上安装 Kivy 的说明?

python - 如何在python中获取用逗号分隔的数字组?

python - 如何在python中处理非常大的文件(13GB)而不会崩溃?

c - 在C中,有没有更好的方法来计算不确定性值?

python - ctypes 结构中数组元素的赋值