Python Ctypes & Threading

ctypes, python

Solution

From Python docs on ctypes:

Important note for callback functions:

Make sure you keep references to CFUNCTYPE objects as long as they are used from C code. ctypes doesn’t, and if you don’t, they may be garbage collected, crashing your program when a callback is made.

If you see "access violation" or "segmentation fault" AND you are dealing with callbacks, that's most probably the reason. As J.F. Sebastian mentioned globals is an option, though I usually maintain a list of references to active callbacks in my class.

When no callbacks are involved, carefully check types in your wrappings. Declaring a wrong type can get ugly and would be hard to figure out.

Problem

To put this into context, I'm creating a wrapper for a C DLL - Fairly convoluted use case but please stick with me! During the init of my wrapper class, I create aliases to my C DLL's functions so my class can access them easily later on. An additional task I do is pass a callback to a function within my class to my DLL, which is saved in a static variable and used later. Finally, I spawn another thread which repeatedly calls a function within my DLL which does some work and at various points within its execution, needs to call back into the Python program using the callback assigned in the init phase of my class. When the callback is invoked in this fashion I receive the following: ``` WindowsError: exception: access violation reading 0x00000001 ``` I suspect this is to do with threading because when I test the callback in the same thread to which I assigned it, the DLL can successfully invoke it and all my arguments get passed across to Python. Is there some protection being enforced over my variable within my DLL which I'm using to persist my callback?

Original source