I am currently investigating interfaces between python and C-dll's. Using the ctypes library, I'm able to load the dll.
I have a very simple software setup for a proof of concept: The function I call in the DLL, expects 1 argument; a function pointer to a function which takes a string to be printed by the python code.
Python code:
lib = ctypes.WinDLL(LIB_PATH)
# 1) Create callback function type
CB_FUNC_TYPE = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p)
# 2) Create the function which will be called back
def foo(text):
print text
# 3) create ctype callback function
cb_func = CB_FUNC_TYPE(foo)
# 4) Call the function
print lib.Test2(cb_func)
Exported C function (Test2):
__declspec(dllexport) void Test2(T_LOG_CALLBACK pf_log)
{
pf_log("Hello Python Log function!);
return;
}
When executing the python code, I get the following error output message:
Hello Python Log function!
Traceback (most recent call last):
File "C:\version\vcs\py\workspace\workspace\tests\python-c integration\test.py", line 32, in <module>
print lib.Test2(cb_func)
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
Which means that the callback is executed correctly, but an error on the stack has been triggered.
I don't understand the error, because the c-function only has one parameter (the function pointer to the function foo in this case).
If I update the line :
cb_func = CB_FUNC_TYPE(foo)
to
print lib.Test2(cb_func, "extra")
I get the same error, but 8 bytes in excess:
Hello Python Log function!
Traceback (most recent call last):
File "C:\version\vcs\py\workspace\workspace\tests\python-c integration\test.py", line 32, in <module>
print lib.Test2(cb_func, "extra")
ValueError: Procedure probably called with too many arguments (8 bytes in excess)
I cannot find the error, as I at least need to add the callback function's address.
Anybody can see what I'm doing wrong?