python, ctypes, callbacks -- access violation when calling callback

2009-07-19 Thread resurtm
Hello.

I'm trying to pass to the C function pointer to callback function from
python. But when i'm trying to do this i get access violation within
the DLL file when calling python callback.

Here is the python side code:

from ctypes import *

# ...

class NewtonBody(Structure):
  def __init__(self, pointer = 0):
 self.pointer = pointer

# ...

class Newton:
  def __init__(self):
 self._cdll = CDLL('newton.dll')
 self.world = NewtonWorld()

# ...

  # NewtonBodySetForceAndTorqueCallback
  def bodySetForceAndTorqueCallback(self, body):
 CALLBACK = CFUNCTYPE(c_int, POINTER(NewtonBody), c_float, c_int)
 def callback(a, b, c):
print '1'
return 0
 self._cdll.NewtonBodySetForceAndTorqueCallback(body.pointer,
CALLBACK(callback))
 return None

Traceback:

Traceback (most recent call last):
 File Newton.py, line 119, in module
   newton.update(10.5)
 File Newton.py, line 42, in update
   self._cdll.NewtonUpdate(self.world.pointer, c_float(timestep))
WindowsError: exception: access violation reading 0x3C99

And finally prototype of function which i'm trying to call and
callback function type declarations:

typedef void (*NewtonApplyForceAndTorque) (const NewtonBody* body,
dFloat timestep, int threadIndex);

// ...

NEWTON_API void  NewtonBodySetForceAndTorqueCallback (const
NewtonBody* body, NewtonApplyForceAndTorque callback);

Can anybody explain my errors when trying to pass callback to DLL
function?

Thanks for advices and solutions!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python, ctypes, callbacks -- access violation when calling callback

2009-07-19 Thread resurtm
On 19 июл, 21:09, Christian Heimes li...@cheimes.de wrote:
 resurtm wrote:
  Can anybody explain my errors when trying to pass callback to DLL
  function?

  Thanks for advices and solutions!

 You have to keep a reference to the callback alive yourself. ctypes
 doesn't increase the refernece counter of the function when you define a
 callback. As soon as the ref counter reaches 0, the function object is
 collected and the pointer to the callback is invalid.

 You could assign it to a module global or instance variable.

 Christian

Thanks for help Christian! It's working fine now! ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list