python(ctypes)中的回调问题

我在 python 中遇到了 CTYPES 的问题。我已经准备好带有一些回调的 dll 库。在 swift 上一切正常,但我在 python 中有一些问题。


Python:


def set_up_callback(self):

    self.lib.set_callback(self.callback1)


@CFUNCTYPE(None, c_float, c_float, c_float, c_uint64)

def callback1( a, b, c, time):

    print(a, b, c, time)

c++回调声明


typedef void(*callbackType)(float, float, float, uint64_t, void*);

        callbackType callback;


void* context;

C++ 初始化


void setCallback(callbackType callback, void* context) {


        this->context = context;

        this->callback = callback;

}

C++ 归纳


callback(1.5f, 2.4f, 1.3f, timestamp, context);

共享.h


extern "C" void SHARED_EXPORT set_callback(callbackType callback, void* context);

这很好用,但我想要selfIn 回调函数,所以我试试这个


def set_up_callback(self):


    callback_type = CFUNCTYPE(None, c_float, c_float, c_float, c_uint64)


    callback = callback_type(self.callback1)


    self.lib.set_callback(callback)


def callback1(self, a, b, c, time):

    print(a, b, c, time)

通过这个尝试我有错误Segmentation fault: 11


预先感谢您的帮助


慕婉清6462132
浏览 148回答 1
1回答

德玛西亚99

In set_up_callback,callback是一个局部变量,在调用 后超出范围self.lib.set_callback(callback)。callback您必须在可以调用的生命周期内保留对的引用,因此将其存储为类实例的成员变量。工作演示:演示.cpp#include <time.h>#include <stdint.h>#if defined(_WIN32)#&nbsp; &nbsp;define API __declspec(dllexport)#else#&nbsp; &nbsp;define API#endiftypedef void(*CALLBACK)(float, float, float, uint64_t, void*);CALLBACK g_callback;extern "C" {API void set_callback(CALLBACK callback) {&nbsp; &nbsp; g_callback = callback;}API void demo(void* context) {&nbsp; &nbsp; if(g_callback)&nbsp; &nbsp; &nbsp; &nbsp; g_callback(1.5f, 2.4f, 1.3f, time(nullptr), context);}}演示.pyfrom ctypes import *from datetime import datetimeCALLBACK = CFUNCTYPE(None,c_float,c_float,c_float,c_uint64,c_void_p)class Demo:&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.lib = CDLL('./demo')&nbsp; &nbsp; &nbsp; &nbsp; self.lib.set_callback.argtypes = CALLBACK,&nbsp; &nbsp; &nbsp; &nbsp; self.lib.set_callback.restype = None&nbsp; &nbsp; &nbsp; &nbsp; self.lib.demo.argtypes = c_void_p,&nbsp; &nbsp; &nbsp; &nbsp; self.lib.demo.restype = None&nbsp; &nbsp; &nbsp; &nbsp; self.set_up_callback()&nbsp; &nbsp; def callback(self,a,b,c,timestamp,context):&nbsp; &nbsp; &nbsp; &nbsp; print(a,b,c,datetime.fromtimestamp(timestamp),self.context)&nbsp; &nbsp; def set_up_callback(self):&nbsp; &nbsp; &nbsp; &nbsp; self.callback = CALLBACK(self.callback)&nbsp; &nbsp; &nbsp; &nbsp; self.lib.set_callback(self.callback)&nbsp; &nbsp; def demo(self,context):&nbsp; &nbsp; &nbsp; &nbsp; self.context = context&nbsp; &nbsp; &nbsp; &nbsp; self.lib.demo(None)demo = Demo()demo.demo([1,2,3])demo.demo(123.456)demo.demo('a context')输出:1.5 2.4000000953674316 1.2999999523162842 2020-04-11 11:38:44 [1, 2, 3]1.5 2.4000000953674316 1.2999999523162842 2020-04-11 11:38:44 123.4561.5 2.4000000953674316 1.2999999523162842 2020-04-11 11:38:44 a context
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python