I am trying to wrap a C library using ctypes. One feature of the library is an ondestroy callback which is called when a handle returned by the library is about to be destroyed.
The callback has the signature:
void cb(f *beingdestroyed);
The API allows one to associate a user-specified void * with f when it is returned by the library. Hence I can associate the py_object being used to wrap it as user data. My plan is to have an is_valid field and when the callback is fired to extract the user_data and set this field to false.
My problem is how to go about extracting my high-level py_object; I can fetch the user data as a ctypes.void_p and cast to a ctypes.py_object but then I’ve only got the Python C API to work with. It is possible to back-cast to a high level object which I can work with by writing user_object.is_valid = 0?
To elaborate on Thomas Heller’s answer:
c_void_pfor the context parameterpy_objectfor the context parameterpy_object(my_python_context_object)cast(context, py_object).valueHere is a working example. Start with C source for a simple DLL:
And here is a Python program that invokes the DLL: