Function References

squishywaffle at gmail.com squishywaffle at gmail.com
Thu Jul 31 09:51:58 EDT 2008


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!



More information about the Python-list mailing list