Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

15 views
Skip to first unread message

resurtm

unread,
Jul 19, 2009, 11:03:21 AM7/19/09
to
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!

Christian Heimes

unread,
Jul 19, 2009, 11:09:37 AM7/19/09
to pytho...@python.org
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

resurtm

unread,
Jul 19, 2009, 11:15:33 AM7/19/09
to

Thanks for help Christian! It's working fine now! ;-)

0 new messages