2

I have the following code:

lib.h

struct Node {
    int index;
    char name[10];
};
void getAllNodes(Node array[]);

libtest.py

from ctypes import *

class Node(Structure):
    _fields_ = [("index", c_uint), ("name", c_char*10)]

lib = CDLL("/path/to/lib.so")

nodeCount = 5
NodeArray = Node * nodeCount
getAllNodes = lib.getAllNodes     
pointers = NodeArray()
getAllNodes(pointers)

casted = cast(pointers, POINTER(NodeArray))
for x in range(0, nodeCount):
    node = cast(casted[x], POINTER(Node))
    print "Node idx: %s name: %s" % (node.contents.index, node.contents.name)

I must be close because the Node struct at index 0 has the correct values but the remainder are gibberish. What am I building incorrectly that's giving me the problem?

1 Answer 1

3

It isn't an array of pointers. It's an array of Node records, laid out contiguously in memory. As a parameter in a function call the array acts like a Node * (pointer to the first item). After the call you can simply iterate the array:

getAllNodes.argtypes = [POINTER(Node)]
getAllNodes.restype = None

nodeArray = (Node * nodeCount)()
getAllNodes(nodeArray)

For example:

>>> [node.name for node in nodeArray]
['node0', 'node1', 'node2', 'node3', 'node4']
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This works well. I'm not sure how I got so far off the beaten path. Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.