1 回答
TA贡献1770条经验 获得超3个赞
In set_up_callback,callback是一个局部变量,在调用 后超出范围self.lib.set_callback(callback)。callback您必须在可以调用的生命周期内保留对的引用,因此将其存储为类实例的成员变量。
工作演示:
演示.cpp
#include <time.h>
#include <stdint.h>
#if defined(_WIN32)
# define API __declspec(dllexport)
#else
# define API
#endif
typedef void(*CALLBACK)(float, float, float, uint64_t, void*);
CALLBACK g_callback;
extern "C" {
API void set_callback(CALLBACK callback) {
g_callback = callback;
}
API void demo(void* context) {
if(g_callback)
g_callback(1.5f, 2.4f, 1.3f, time(nullptr), context);
}
}
演示.py
from ctypes import *
from datetime import datetime
CALLBACK = CFUNCTYPE(None,c_float,c_float,c_float,c_uint64,c_void_p)
class Demo:
def __init__(self):
self.lib = CDLL('./demo')
self.lib.set_callback.argtypes = CALLBACK,
self.lib.set_callback.restype = None
self.lib.demo.argtypes = c_void_p,
self.lib.demo.restype = None
self.set_up_callback()
def callback(self,a,b,c,timestamp,context):
print(a,b,c,datetime.fromtimestamp(timestamp),self.context)
def set_up_callback(self):
self.callback = CALLBACK(self.callback)
self.lib.set_callback(self.callback)
def demo(self,context):
self.context = context
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.456
1.5 2.4000000953674316 1.2999999523162842 2020-04-11 11:38:44 a context
添加回答
举报