Wrapping a C library in Python

Roy Smith roy at panix.com
Mon Nov 22 07:56:55 EST 2004


In article <hdnip9ey.fsf at python.net>,
 Thomas Heller <theller at python.net> wrote:

> > 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))

I guess that makes sense.  In my case, however, the structure has about 
20 elements, many of which are user-defined types.  Building the correct 
ctypes.Structure description would be a bit of work, and it would 
certainly violate the rule of "once and only once".  If the underlying C 
structure changed, I'd have to update my Python code to match.

Since the handle is opaque, I don't need to know about the innards of 
the structure at all.  What I ended up doing was writing a little C 
routine something like this:

dm_handle *allocate_dm_handle ()
{
   return malloc (sizeof (struct dm_handle));
}

I then built a .so containing just that one routine, and used ctypes to 
call it from Python to get my buffer.



More information about the Python-list mailing list