I have to define a callback function in Python, one that will be called from a DLL.
BOOL setCallback (LONG nPort, void ( _stdcall *pFileRefDone) (DWORD nPort, DWORD nUser), DWORD nUser);
I tried this code, that seems to work in Python 2.5 but with Python 2.7 it crashes and I assume I did something wrong.
import ctypes, ctypes.wintypes
from ctypes.wintypes import DWORD
def cbFunc(port, user_data):
print "Hurrah!"
CB_Func = ctypes.WINFUNCTYPE(None, DWORD, DWORD)
mydll.setCallback(ctypes.c_long(0), CB_Func(cbFunc), DWORD(0))
Where is the mistake?
Note: The platform is running on 32bit only (both Windows and Python). The DLL loads successfully and also other functions from inside do work just fine while called from Python.
A full sample code that reproduces this is available at https://github.com/ssbarnea/pyHikvision - just run Video.py under py25 and py27.
In the context of Video class using a nested function:
It is somewhat ugly but a more natural variant fails with TypeError during callback:
To fix that a special function descriptor could be created:
Usage:
Additionally MethodDescriptor saves references to C functions to prevent them being garbage collected.