Sunday, August 09, 2009

Using Python ctypes to access C lib global data

I want to access global data in a C library from within a Python program. The Python ctypes documentation tells you how to call functions, set up arguments and other things. But if you want to access global data, well, the doc is lacking a good example. This may help. (I'm assuming you are generally familiar with ctypes.)

Suppose you have a C library with several functions and a single global data item named "myGlobal" of type unsigned long. Load the library as "lib" and you can access myGlobal with this snippet.
    myGlobal = c_ulong.in_dll(lib, "myGlobal").value
print(" myGlobal = %d" % myGlobal)
If you have several global variables and have organized them as a C struct named "G"....
    struct {
// reference with a "G." prefix
unsigned long value1;
unsigned long value2;
unsigned long value3;
} G;
...your Python code might include a snippet like this.
    class AllMyGlobals(Structure):
_fields_ = [("value1", c_ulong),
("value2", c_ulong),
("value3", c_ulong)]

G = AllMyGlobals.in_dll(lib, "G")
print(" G.value1 = %d" % G.value1)
print(" G.value2 = %d" % G.value2)
print(" G.value3 = %d" % G.value3)
Changing one of those values in the C library is easy too.
    G.value2 = 1234

Labels: ,