ctypes回调函数崩溃了Python - "这个"指针参数?

时间:2015-03-30 06:44:53

标签: python c++ this ctypes this-pointer

我使用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中我有以下代码(仅显示相关部分),在触发事件后不久就会崩溃Python(没有追溯)并且打印出callback run!

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

在我的Python类中,我可以发送的this等同于最后一行代码中的c_void_p()?即使在我的Python回调函数触发后,获取此参数错误也会导致崩溃吗?

0 个答案:

没有答案