[Pyrex] Callbacks

Daniele Pianu muogoro at gmail.com
Fri May 9 12:36:02 CEST 2008


I also solve the problem putting func, data references couples into a list.
Since the list is a PyFooStruct attribute, func/data references will never
be decremented until the PyFooStruct is used. Could be a better solution
than the first solution suggested?

cdef extern from 'foo.h':
  struct FooStruct:
    pass
  FooStruct* Foo_new()
  int Foo_call(FooStruct* self, int indexFunc)
  int Foo_addFunc(FooStruct* self, void(*func)(void*), void* data)
  int Foo_fire(FooStruct* self)
  void Foo_destroy(FooStruct* self)


cdef void PyCallback( object funcAndData):
  cdef object func, data
  func = funcAndData[0]
  data = funcAndData[1]
  func(*data)

cdef class PyFooStruct:
  cdef FooStruct* selfPtr
  cdef object tmpFuncAndData

  def __init__(self):
      self.selfPtr = Foo_new()
      self.tmpFuncAndData = []

  def PyFoo_call(self, i):
    return Foo_call(self.selfPtr, i)

  def PyFoo_addFunc(self, func, data):
      cdef object tmpFuncAndData
      tmpFuncAndData = (func, data)
      self.tmpFuncAndData.append(tmpFuncAndData)
      return Foo_addFunc(self.selfPtr, <void(*)(void*)>PyCallback, \
                             <void*>tmpFuncAndData)

  def PyFoo_fire(self):
      return Foo_fire(self.selfPtr)

  def __dealloc__(self):
      Foo_destroy(self.selfPtr)


2008/5/9 Robert Bradshaw <robertwb at math.washington.edu>:

> On May 9, 2008, at 2:42 AM, Daniele Pianu wrote:
>
> [...]
>
>  Is there a way to solve the problem without importing anything from
>> Python.h?
>>
>
> No, unless you want to cache of the func/data manually somewhere else. Also
> note that this may cause a memory leak, as the reference count will never be
> decremented.
>
> - Robert
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.copyleft.no/pipermail/pyrex/attachments/20080509/76a1c8a3/attachment.html 


More information about the Pyrex mailing list