gpt4 book ai didi

Python:从回调访问对象属性

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:51 24 4
gpt4 key购买 nike

我正在尝试设计带有回调函数的类,该回调函数被传输到某个 C 库。需要在不更改回调参数的情况下授予对此类对象的访问权限。如何做到这一点?

from ctypes import *
...
lib = CDLL('mylibname.so')
...
class A(object):
def __init__(self):
CALLBACK = CFUNCTYPE(c_uint32, c_void_p)
self.callback_func = CALLBACK(A.message_callback)
self.param = None
def message_callback(data):
... #here need access to self.param
return 0
def set_param(self, param):
self.param = param
...
a = A()
lib.lib_func(param1, param2, a.callback_func)

编辑:我用包装函数更改了类中的回调方法:

from ctypes import *
...
lib = CDLL('mylibname.so')

class struct_t(Structure):
pass
struct_t._fields_ = [('next', POINTER(value_pair_t)),
('key', c_char_p),
('value', c_char_p)]
...
class A(object):
def __init__(self):
self.param = None

def wrapper(self):
CALLBACK = CFUNCTYPE(c_uint32, POINTER(struct_t))
def message_callback(data):
... # now I have access to self here
return 0
return CALLBACK(message_callback)

def set_param(self, param):
self.param = param
...
a = A()
lib.lib_func(param1, param2, a.wrapper())

它在 python2 中有效,但我在 python3 中仍然有问题:

追溯(最近的调用最后): 文件“_ctypes/callbacks.c”,第 260 行,在“调用回调函数”中类型错误:“LP_struct_t”对象不可调用

这是同一问题的链接:Weird bug?

最佳答案

只需定义 message_callback(self, data) 并使用 self.callback_func = A.CALLBACK(self.message_callback)。请注意,我使用了 A.CALLBACK。将其设置为类属性。为每个实例定义它是浪费时间。

例如:

C:

typedef int (*callback_t)(void *data);

int test(const char *data, callback_t f) {
f((void *)data);
return 0;
}

python :

from ctypes import *

class A(object):
CALLBACK = CFUNCTYPE(c_uint32, c_void_p)

def __init__(self):
self.callback_func = A.CALLBACK(self.message_callback)
self.param = None

def message_callback(self, data):
self.param = cast(data, c_char_p).value
return 0

演示:

>>> lib = CDLL('./lib.so')
>>> a = A()
>>> lib.test.argtypes = [c_char_p, A.CALLBACK]
>>> lib.test("updated", a.callback_func)
0
>>> a.param
'updated'

关于Python:从回调访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20377429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com