繁体   English   中英

使用ctypes在Python中读取C结构

[英]Reading C structures in Python with ctypes

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

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM