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
添加回答
舉報