[Tutor] How to make a python binding for a c library?

Mark Tolonen metolone+gmane at gmail.com
Tue May 13 08:31:56 CEST 2008


"tuyun" <twomol at hotmail.com> wrote in message 
news:BAY108-W54DF95D77BED99541362E2CDCF0 at phx.gbl...
> Hi
> I have a library written in C, I want to make a python binding for it.
> But I dont know how to get started.
> Is there any guide or document?
> Is "Python/C API Reference Manual" the right doc I need to study first?

Check out the ctypes library.  It comes with Python 2.5, but can be 
installed for older versions.

Here's an example that calls the Win32 function Beep() from kernel32.dll:

import ctypes
ctypes.windll.kernel32.Beep(440,1000)

This is a simplistic example that works for simple DLL functions that take 
integers and return integers.  If your APIs deal with pointers and 
read/write buffers it is somewhat more complicated, but still easier to 
write your bindings in Python than using the Python C APIs.

-Mark




More information about the Tutor mailing list