Use Pyrex instead (Re: newbie at SWIG, help needed with typemaps)

Duncan Booth duncan at
Tue Apr 1 10:43:58 CEST 2003

achrist at wrote in news:3E87E64C.F7D2C11E at

> "Greg Ewing (using" wrote:
>> Instead of SWIG, you might prefer to use Pyrex to wrap your C code:
>> This is exactly the sort of problem I designed Pyrex to solve.
> Looks almost too nice to be true.  Any reliability or performance
> issues?
> Any reason to think this won't work with Windows and MSVC?

I'm giving a talk at the UK Python conference about integrating Python with 
C/C++, so I've been playing about with Pyrex a bit recently. I can highly 
recommend it.

Remember it is still a work in progress. This means that if you really push 
the envelope, you may find some areas where it becomes less friendly[1], 
probably because nobody else has been there before you. However, most of 
the time it will really amaze you. When you get an extension written using 
the C Api or SWIG wrong, you spend an age in the debugger. When you get 
your Pyrex extension wrong, you get a Python exception and stack backtrace.

If you use Distutils to do the compilation then you won't even have to 
worry about what compiler options to use: your extension will compile on 
anything that has a compiler. If you want to write your own makefiles you 
may have to think a bit harder, but I can post a simple Pyrex makefile for 
msvc if anyone wants it (actually I'll make a point of putting my talk 
slides and associated examples on the web after the conference).

My only other complaint would be that the documentation is perhaps a little 
bit sparse. Probably it just needs some more examples.

[1] An example where it becomes less friendly. The documentation says that 
to do class methods you have to write the function outside the class:

    	def Spam_method(cls):

     class Spam:
    	    	method = classmethod(Spam)

I, of course, misread this and wrote:

     cdef class Spam:
    	    	method = classmethod(Spam)

This gives an error from the C compiler: 'method' undeclared identifier.
Fair enough that it doesn't work (the documentation sort of says it won't), 
but not so good that it generated bad C code. (For those who don't know 
Pyrex, 'class Spam' generates a Python class 'Spam', 'cdef class Spam' 
generates a new built-in type 'Spam'.)

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list