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?

Eryk Sun
34.5k7 gold badges97 silver badges113 bronze badges
asked May 23, 2013 at 1:49

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']
answered May 23, 2013 at 9:32
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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.