calling Pyrex results from C
François Pinard
pinard at iro.umontreal.ca
Tue Jan 20 12:27:33 EST 2004
[Kyler Laird]
> I realize that the goal of Pyrex is to create a module that can be
> called from Python.
Or vice-versa. I found Pyrex useful for calling Python modules from
within C programs which were not Python-aware to start with. You may
even write wholly Pyrex programs.
> 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.
There is some magic needed to establish Python context, not much.
Hoping that it will help, here is a template I use when generating
Pyrex main programs. `%(module)s' shall be replaced by the Pyrex module
name, as Pyrex needs to initialise itself. When Python calls Pyrex,
initialisation occurs automatically at `import' time, but when C
initially calls Pyrex, initialisation should be explicitly launched.
cdef extern void Py_Initialize()
cdef extern void Py_Finalize()
cdef extern void init%(module)s()
cdef extern int main(int argc, char **argv):
cdef int index, status
Py_Initialize()
init%(module)s()
import sys
try:
arguments = []
for index from 0 <= index < argc:
arguments.append(argv[index])
sys.argv = arguments
result = main_application()
raise SystemExit, result or 0
except SystemExit, result:
result = str(result)
try:
status = int(result)
except ValueError:
if not result.endswith('\n'):
result = result + '\n'
sys.stderr.write(result)
status = 1
except:
import traceback
traceback.print_exc()
status = 1
Py_Finalize()
return status
--
François Pinard http://www.iro.umontreal.ca/~pinard
More information about the Python-list
mailing list