簡體   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