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

R

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 0x3C888899

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!
 
R

resurtm

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! ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,531
Members
45,004
Latest member
KetoBoostGummies

Latest Threads

Top