C DLL to Python Callback

风流意气都作罢 提交于 2020-01-24 15:28:29

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/21011620/c-dll-to-python-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!