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
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
Eryk Sun
34.5k7 gold badges97 silver badges113 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
bitwit
Thank you. This works well. I'm not sure how I got so far off the beaten path. Cheers.
lang-py