Re: using c-methods for callbacks?

Robert Bradshaw <[email protected]> Sat, 30 May 2009 08:35:13 -0700
Newsgroups gmane.comp.python.pyrex
Message-ID <[email protected]>
On May 29, 2009, at 9:00 PM, Lenard Lindstrom wrote:

> horace wrote:
>> hi,
>>
>> it would be great if i could use c-methods for callbacks but i always
>> get a crash if i access self. am i doing something wrong or doesn't
>> self get assigned correctly if the method gets called from a c- 
>> library?
>>
>> cdef class Engine:
>>   ...
>>   cdef void on_space(self): # i pass this to the c-library to be used
>> as the callback
>>     print "test!" # this works
>>     print self # this crashes
>> --------------------------------------------------------------------- 
>> ---
>>
>> _______________________________________________
>> Pyrex mailing list
>> [email protected]
>> http://lists.copyleft.no/mailman/listinfo/pyrex
>>
> ctypes creates C closures through libffi. That binds the self argument
> with a value. Cython won't do that. It requires assembly code, so  
> is not
> portable. You either have to get your function's arguments through
> global variables or hope the callback mechanism includes an argument
> passing mechanism. If that later, I don't know exactly how to  
> convert a
> Python object to a void pointer and back in Cython. If the  
> callbacks are
> passed a keyboard key argument by the caller then that could be  
> used as
> a key into a dictionary of Python functions.

You can write <void*>foo to convert from an object to a void* (and  
<object>x to go the other way), but note that if you do this it is  
your job to make sure the object doesn't go out of scope/get  
deallocated while the callback can still be called. If speed is not a  
concern, sticking it in a dict and using an int to retrieve it is a  
great idea.

- Robert