[Pyrex] "Dynamic" callbacks?

Timothy Toroni timothy at torpedogames.com
Mon Mar 21 07:07:59 CET 2005


Hello all,

I've got a C library with timers which provide callbacks.  I can 
successfully use the callback as per the demo find cheese example.  
However it uses a cdef function as the actual callback, and suppose you 
can't use a "userdata" data passback, is it possible to "CLASSify 
this?"  For example,

cdef CLibFunctionRegisterCallback( void (*func)(void), timeout )

cdef class Timer:
    def __init__(self, python_callback_function, timeout):
        self.python_callback_function = python_callback_function
        CLibFunctionRegisterCallback( <void *> self.c_callback, timeout)
       
    cdef void c_callback(self):
        self.python_callback_function()


Is something like this possible?  Problem is I'm not sure how to deal 
with the 'self' parameter in the callback which seems to be required.  
My thoughts are if I'm able to stick the C callback in the class I can 
create as many C callback functions as needed, otherwise I'll have to 
write a small Pyrex callback broker for a fixed number of callbacks - 
which I'd rather not do --> is this the only solution!?!

Ideally you'd to able to pass python functions directly to the Clib as a 
callback...

It appears that you can do a similiar "classification" with SWIG (from 
/Examples/python/callback/):

/* File : example.h */

#include <cstdio>
#include <iostream>

class Callback {
public:
    virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: 
endl; }
    virtual void run() { std::cout << "Callback::run()" << std::endl; }
};


class Caller {
private:
    Callback *_callback;
public:
    Caller(): _callback(0) {}
    ~Caller() { delCallback(); }
    void delCallback() { if (_callback) delete _callback; _callback = 0; }
    void setCallback(Callback *cb) { delCallback(); _callback = cb; }
    void call() { if (_callback) _callback->run(); }
};



2nd)
Should I be able to store pointers (like a void*) in Python then pass it 
back to a C function?  Since it appears I cannot pass void * pointers 
back to Python directory I tried typecasting to <long>, then recasting 
to a pointer again in Pyrex... but no go.  Is there a way to store 
pointers from Pyrex in Python?  The library keeps blowing up when I do 
the typecasting thing.

73,
Timothy





More information about the Pyrex mailing list