calling Pyrex results from C

Kyler Laird Kyler at news.Lairds.org
Tue Jan 20 10:22:03 EST 2004


I need to submit C/C++ code for a class.  (It's not a programming
class.  The choice of language is inertial.  I think that it mostly
serves to distract students from the course subject.)  I'm fairly
fluent with C but it hurts to think about writing in C when Python
is *so* much more appropriate for these operations.

I'd like to keep my sanity and satisfy the course requirements by
programming in Python and converting the code to C.  It looks like
a few people have scratched this itch already, but of the
translators I found, most of them (Python2C, P2C, PyFront) seem to
be dead.  Pyrex, however, appears to be well-maintained and is even
available as a Debian package.
	http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/

I realize that the goal of Pyrex is to create a module that can be
called from Python.  For my need of calling the result from C, the
other utilities are probably more appropriate but I think that
Pyrex could be useful to me for less contrived situations than this
so it's worthwhile to learn more about it.


	http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/version/Doc/overview.html#InterfacingWithExternal

	You can also use public declarations to make C functions
	and variables defined in a Pyrex module available to
	external C code. The need for this is expected to be less
	frequent, but you might want to do it, for example, if you
	are embedding Python in another application as a scripting
	language. Just as a Pyrex module can be used as a bridge to
	allow Python code to call C code, it can also be used to
	allow C code to call Python code.

	[...]

	You can make C variables and functions defined in a Pyrex
	module accessible to external C code (or another Pyrex
	module) using the public keyword

I've discovered that as long as everything in the code is cdef-ed,
I can call Pyrex code from my C code.  If, however, I so much as
mention anything Pythonish, it segfaults during execution.

For example, this is fine.
	cdef public int foo():
		cdef int i
		i = 123

		return(i)

And this results in a segfault.
	cdef public int foo():
		cdef int i
		i = 123
		j = 5

		return(i)

This means that I can't, for example, make a function that takes a
filename (string), uses PIL to do a bunch of operations, and
returns a string.

Any suggestions (besides "suck it up and do it all in C")?

Thank you.

--kyler



More information about the Python-list mailing list