[Pyrex] Calling Pyrex from another Python module
Nicholas Riley
njriley at uiuc.edu
Mon Jan 8 22:09:32 UTC 2007
On Thu, Jan 04, 2007 at 07:55:44AM +0100, konrad.hinsen at laposte.net wrote:
> Much of my code does C-function calls between two extension modules
> written in C. Each module makes its callable C functions visible
> through a CObject. The calling module obtains this CObject through
> the standard import mechanism. At some time I wrote a section about
> this mechanism for the "Python extending and embedding" manual; I
> suppose it's still in there.
Yes, thanks, I found that very useful. I was hoping for a
Pyrex-specific method but there doesn't seem to be one (or, really,
any need for one).
> I have never used this approach with Pyrex, but I don't see why it
> shouldn't be possible, given that Pyrex can create pretty much any C
> code.
The only issue is that Pyrex appears to be unable to create static
arrays easily, that I could figure out, so I just put the object
directly into the module namespace instead.
I declared my function as follows:
cdef public void MROWatcher_OnChangeRespawn(type_, name,
void *write_jmp, void *codestart):
then created a PyCObject:
cdef extern from "cobject.h":
object PyCObject_FromVoidPtr(void *cobj, void (*destruct)(void *))
_MROWatcher_OnChangeRespawn = \
PyCObject_FromVoidPtr(<void *>MROWatcher_OnChangeRespawn, NULL)
and called it from C, where I made use of the prototype exported by
Pyrex:
#include "pyUFO.h"
[...]
static typeof(MROWatcher_OnChangeRespawn) *OnChangeRespawn = NULL;
if (OnChangeRespawn == NULL) {
PyObject *c_object =
PyObject_GetAttrString(UFOModule, "_MROWatcher_OnChangeRespawn");
assert(c_object != NULL);
OnChangeRespawn = (typeof(MROWatcher_OnChangeRespawn) *)
PyCObject_AsVoidPtr(c_object);
Py_DECREF(c_object);
}
OnChangeRespawn(type, name, rs->write_jmp, rs->self->codestart);
The latter could be encapsulated in a macro pretty easily, but right
now this is the only function I need to call from C.
--
Nicholas Riley <njriley at uiuc.edu> | <http://www.uiuc.edu/ph/www/njriley>
More information about the Pyrex
mailing list