[Pyrex] python callback appended to external C struct
Elias Pschernig
elias at users.sourceforge.net
Sun Dec 4 23:10:04 CET 2005
On Sun, 2005-12-04 at 13:34 -0800, Lenard Lindstrom wrote:
> I was curious myself if anyone knew of a safe way to go from a Python
> object to void pointer and back in Pyrex. Why not use a module level
> dictionary instead that maps object instances by object id.
> Wrap.__new__ would add the new object to the dictionary, and a
> Wrap.__dealloc__ would remove it. Then CWrapPositionPyrex.self is the
> id, as an integer, and dummy_cd retrieves the actual object from the
> dictionary and calls its cb method.
That's a great idea. Actually, I do not even need the "self" anymore at
all then.. and also not the CWrapPositionPyrex struct. I simply map the
pointer of the C struct to my python object.
I tried it out below.. but one think I'm wondering, is the <int> the
right way to do it? Without it, pyrex would complain. I simply need to
somehow use the C struct as dictionary key..
---- cfoo.h ----
typedef struct CFoo CFoo;
struct CFoo
{
void (*cb)(CFoo *self);
};
---- cfoo.c ----
#include "cfoo.h"
/* In reality, the callback is called at arbitrary times from the C
library. */
void cfoo_callback_test(CFoo *self)
{
self->cb(self);
}
---- foo.pyx ----
cdef extern from "cfoo.h":
ctypedef struct CFoo:
void *cb
void cfoo_callback_test(CFoo *self)
dict = {}
cdef dummy_cb(CFoo *pointer):
self = dict[<int>pointer]
self.cb()
cdef class Foo:
cdef CFoo cfoo
def __new__(self):
self.cfoo.cb = <void *>dummy_cb
dict[<int>&self.cfoo] = self
def callback_test(self):
cfoo_callback_test(&self.cfoo)
---- test.py ----
import foo
class MyPythonClass(foo.Foo):
def cb(self):
print "hello from", self.name
my_python_object = MyPythonClass()
my_python_object.name = "my_python_object"
my_python_object.callback_test()
[PS: I hate lists who set the reply address to the poster.. I always
forget to reply to the list in that case o_O]
--
Elias Pschernig
More information about the Pyrex
mailing list