简体   繁体   中英

C DLL to Python Callback

I have a Visual C++ DLL. I have a SetCallback( function-pointer) exported in the DLL. I use this function to set a callback function from a python2.7 script. I follow what is given in the Python documentation.

from ctypes import *
def mypy_callback(number):
    print str(number)

d = cdll.LoadLibrary(r"myfunctions.dll")
callback_type = CFUNCTYPE(None, c_int )
d.SetCallback(callback_type(mypy_callback))

In the C code I have

typedef void (*callback_function)(int);
void SetCallback(callback_function aCallback)
{
    py_callback = aCallback;
}

When I call this function from C DLL, like so: py_callback(999), python just crashes. What could I be doing wrong?

The following callback indirection will solve this problem:

d = cdll.LoadLibrary(r"myfunctions.dll")
callback_type = CFUNCTYPE(None, c_int )
callback = callback_type(mypy_callback)
d.SetCallback(callback)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM