Python Ctypes & Threading

To put this in context, I create a wrapper for the C DLL - a rather confusing use case, but please stick with me!

During the initialization of my wrapper class, I create aliases for my DLL functions, so my class can easily access them later. An additional task that I perform is to pass a function call inside my class to my DLL, which is stored in a static variable and used later.

Finally, I create another thread that repeatedly calls a function in my DLL, which does some work and at various points in its execution, needs a callback to the Python program using the callback assigned during the initialization phase of my class.

When the callback is called this way, I get the following:

WindowsError: exception: access violation reading 0x00000001 

I suspect this is due to threading, because when I test the callback in the same thread that I assigned it to, the DLL can successfully call it, and all my arguments are passed through Python. Is there some kind of protection applied to my variable in my DLL that I use to save my callback?

+4
source share
1 answer

From Python docs to ctypes:

Important note for callback functions:

Make sure you keep references to CFUNCTYPE objects if they are used from C. ctypes doesnt code, and if you do not, they can be garbage collected, your program crashes on callbacks.

If you see “access violation” or “segmentation error” and you are dealing with callbacks, this is most likely the reason. As noted by Yu.F. Sebastian, global variables are an option, although I usually maintain a list of links to active callbacks in my class.

If callbacks are not involved, carefully check the types in your packages. An ad of the wrong type can become ugly and difficult to understand.

+2
source

Source: https://habr.com/ru/post/1493248/


All Articles