Python ctypes: dereferencing a pointer to a C structure

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() = 17

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: