Function References

Diez B. Roggisch deets at nospam.web.de
Thu Jul 31 09:59:56 EDT 2008


squishywaffle at gmail.com wrote:

> Greetings,
> 
> I'm trying to wrap a function in a C library as a compiled C Python
> module. Everything is going great, but I've hit a snag. There's a
> function in the form of this:
> 
> First the typedef:
> typedef void(*FPtr_DeviceMessageHandler) (const DeviceMessage, const
> char*);
> 
> Then the actual function prototype:
> FPtr_DeviceMessageHandler
> RegisterDeviceMessageHandler(FPtr_DeviceMessageHandler);
> 
> Whenever this USB device I'm using generates a message, it's then sent
> to that function whose reference you passed to
> RegisterDeviceMessageHandler(). Here's an example:
> 
> void testfunc() {
>   printf("test");
> }
> ...on to main()
> RegisterDeviceMessageHandler(&testfunc)
> 
> So I've defined a similar function on my C module to do just this,
> using the passed function reference to allow the device to send
> messages to a Python function of the user's choice. I'm just not sure
> how to do this, and the tutorials I've been digging through don't
> offer any help. I've found some functions that look promising, but
> can't figure out how to cast the function reference from Python into
> something the C RegisterDevice... function can handle. Here's what
> I've got:
> 
> static PyObject *
> Py1_RegisterDeviceMessageHandler(PyObject *self, PyObject *args)
> {
>     PyObject *handle, *parsed;
> 
>     if(!PyArg_ParseTuple(args, "O", handle)) {
>         return NULL;
>     }
> 
>     parsed = PyMethod_Function(handle);
>     I1_RegisterDeviceMessageHandler(PyMethod_Function(handle));
> 
>     Py_RETURN_TRUE;
> } // end Py1_RegisterDeviceMessageHandler()
> 
> This fails since  PyMethod_Function returns a PyObject. Is there a way
> to cast this to something generic? Casting to (void*) didn't seem to
> work.
> 
> Thanks in advance!

May I suggest you move to ctypes for wrapping? It's easier, pure python and
callbacks are already built-in.

Diez



More information about the Python-list mailing list