Archive

Monthly Archives: January 2012

Python’s ctypes library lets you load a dynamically-loaded C library (.so, .dll, .dylib depending on platform) and access the symbols within (call functions, etc).

The documentation is quite good, but here’s something that I didn’t immediately find an answer to.

Suppose you have a C structure, and a function that returns a pointer to such a structure:

struct foo {
    int bar;
};

struct foo *newfoo () {...}

In Python, you want to access the members of the struct foo returned by a function. How do you do it?

First, you need to define a Python class that represents struct foo:

class Foo (ctypes.Structure):
    _fields_ = [ ("bar", c_int) ]

Next, you need to tell ctypes that newfoo() returns a pointer to such a thing:

mylib.newfoo.restype = POINTER(Foo)

Finally, after invoking newfoo(), you need to use the pointer’s contents member to dereference it:

p = mylib.newfoo()
p.contents.bar = 17
Advertisements
%d bloggers like this: