Reading C structures in Python with ctypes

I use ctypes to call foreign functions in Python3.

The C function should return a pointer to the structure:

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

typedef struct sLinkedList* LinkedList;

And the function, as defined in C, is as follows.

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

So, I have Python3 code as follows:

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)

The IedConnection parameter is retrieved by another function as a pointer, and I'm sure it works fine. I also see that the function itself works fine (it initiates the communications that can be seen in Wireshark).

Then I try to get the information as a result of the function:

LogicalDevicesList_p = cast(LogicalDevicesPtr,POINTER(LinkedList))

LogicalDeviceList = LogicalDevicesList_p.contents

These lines pass and the following line does not work:

Rdata = LogicalDeviceList.data

with "Segmentation Error: 11"

I suppose the problem is if with type definitions, but I have no idea where the error is. Can anyone help?

+4
1

, , :

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

Source: https://habr.com/ru/post/1651309/


All Articles