Pyrex and sharing extension modules
I’m using Python and C in one of the rather large projects I’m working on, and I’m using Pyrex to provide the bridging code. Once I got over some of the tricks involved in sharing types between extension modules, it was cooking with gas.
Now I have a Firewire camera running live in a wxPython window being displayed using PyOpenGL. Very cool indeed… Now all I have to do is hack in YUV support into Gandalf, and I’ll be set!
Writing extension modules in Pyrex is dead easy, sharing them just takes a little extra know-how. You have to declare the cdef functions along with the data members in your .pxd file. Then the implementation goes into the .pyx module, which is compiled. The trouble I came across was calling cdefed functions between modules that used a common C type defined in another module. Clear as mud?
The solution was to declare the C typedefs in their own .pxd and import those into both, thus putting all the C types in their own namespace. Then two different extension modules can use the same C types from Pyrex code and all’s well.
2013 Update
These days, you would likely use the ctypes
module, which allows you to transparently
invoke C functions from Python code.