Sending arrays of a structure as an argument via ctypes

Knut Saua Mathiesen ks.mathiesen at gmail.com
Mon Jun 23 06:28:50 EDT 2008


Hi there.
I am reprogrammed my astar* path finding algorithm in C to make it quicker.
I am now trying to make python use this C extension, however I keep
getting "Segmentation fault".

Some of the C stuff:



typedef struct Point {
	int x;
	int y;
} Point;

typedef struct Node {
	Point pos;
	int cost;
	int g;
	int obstacle;
	struct Node* parent;
} Node;

void astar(Node map[], Point from, Point to) {
	(...)
}
main () {
	(...)
	Node map[maptotal];
	(...)
	astar(map, createPoint(0,0), createPoint(50,50));
}


Now I am by no means a C programmer, this is basicly the first "bigger
than hello-world" program, but I have got it working in C. What I am
now trying to do is to make the map using python, and send it to my
astar C function using ctypes.

Basicly I've rewritten my structures in python:


class Point(Structure):
	_fields_ = [("x", c_int), ("y", c_int)]
	def __repr__(self): return "<Point:%s,%s>" % (self.x, self.y)

class Node(Structure):
	def __repr__(self):
		return "<Node:(%s,%s)>" % (self.pos.x, self.pos.y)
Node._fields_ = [('pos', Point), ('cost', c_int), ('g', c_int),
('obstacle', c_int), ('parent',POINTER(Node))]



And after that, this is how I am trying to call it:

	self.astar = astarlib.astar
	self.astar.argtypes = [Node * self.maptotal, Point, Point]
	self.astar.restype = None

	self.nodes = (Node * self.maptotal)()
	for i in range(self.mapwidth):
		for i2 in range(self.mapheight):
			self.nodes[i2 * self.mapwidth + i] = Node(Point(i, i2))

	self.astar(self.nodes, Point(5,6), Point(6,6))


When I call the self.astar function it segfaults. And what I think
I've done wrong is the self.nodes part, but I can't find any good
documentation on it.

Any help? :p



More information about the Python-list mailing list