0

我正在使用 ctypes 从 Python 调用 C dll,并且在将正确的参数传递给IBSU_RegisterCallbacks下面定义的函数时遇到了一些麻烦。

int WINAPI IBSU_RegisterCallbacks
    (const int         handle, 
     const IBSU_Events event, 
     void             *pCallbackFunction,
     void             *pContext);

它将最终参数描述为:

/* pContext Pointer to user context that will be passed to callback function.*/

一个有效的 C++ 示例调用该函数,如下所示:

RegisterCallbacks(0, 1, OnCallback, this);

到目前为止,在 Python 中,我有以下代码(仅显示相关部分),它在事件触发并callback run!打印后不久使 Python 崩溃(无回溯)。

from ctypes import *

class IBSU(object):
    _dll = WinDLL('ibsu.dll')

    _C_CALLBACK = CFUNCTYPE(
        None,        
        c_int,                                         # device handle
        c_void_p)                                      # user context

    _register_callbacks = _dll.IBSU_RegisterCallbacks
    _register_callbacks.restype = c_int
    _register_callbacks.argtypes = (c_int,             # device handle
                                    c_int,             # event type
                                    c_void_p,          # callback function
                                    c_void_p)          # user context

    def _get_c_callback(self):
        def callback(handle,                           # device handle
                     p_context):                       # user context
            print 'callback run!'
        return self._C_CALLBACK(callback) 

    def register_callbacks(self):
        # keep ref to prevent garbage collection
        self._c_callback = self._get_c_callback()

        self._register_callbacks(0,                    # device handle
                                 1,                    # event type
                                 self._c_callback,     # callback function
                                 c_void_p())           # user context

this在我的 Python 类中,我可以发送而不是仅c_void_p()在最后一行代码中的等价物是什么?即使在我的 Python 回调函数触发后,错误地获取此参数也会导致崩溃吗?

4

0 回答 0