Wrapping a C library in Python

Thomas Heller theller at python.net
Mon Nov 22 03:36:37 EST 2004


Roy Smith <roy at panix.com> writes:

> loritsch at gmail.com (Michael Loritsch) wrote:
>> If speed of development is your main goal, then I'd use ctypes. 
>> ctypes will dynamically load the library in python code.  At the
>> python code level, you should then do the translation to python types.
>>  No C/C++ coding required.
>
> OK, I decided to give ctypes a try.  After a few false steps (mostly 
> related to sorting out LD_LIBRARY_PATH issues), I got it to work for 
> simple functions.  Once you get your head around how it works, it's 
> pretty neat.
>
> The problem is, I'm at a loss what to do for a slightly more complex 
> case.  The API I'm working with requires that you create a dm_handle 
> which you then pass into all the other calls to establish a context.  
> You start with (approximately):
>
> /*
>  * Create a handle.  The caller must have allocated memory for
>  * the object pointed to by dmh.
>  */
> create_dm_handle (struct dm_handle *dmh);
>
> I don't see how I can do the required memory allocation.  Calling 
> malloc() directly seems kind of scary.  Even if I could do that, doing 
> sizeof (struct dm_handle) won't work in the Python environment.
>
> Am I missing something obvious here?

It's simple.
First, you define the structure:

import ctypes
class dm_handle(ctypes.Structure):
    _fields_ = [....] # whatever is is

Then, create an instance (this will allocate memory internally)

my_handle = cm_handle()

and finally call the function, pssing it a pointer to the structure:

mydll.create_dm_handle(ctypes.byref(my_handle))

Thomas



More information about the Python-list mailing list