我试图为一个名为虚拟天堂的应用程序设计一个机器人程序,而用来构建机器人程序的SDK被编译成一个共享库,因此我不得不使用ctypes。在
当我使用
import threading
...
from ctypes import CDLL, CFUNCTYPE, c_char_p, c_int, c_void_p
vp = CDLL("libvpsdk.so")
vp.vp_string.restype = c_char_p
vp.vp_int.restype = c_int
...
class bot(threading.Thread):
def initBot(self):
...
instance = vp.vp_create()
...
EventFunc = CFUNCTYPE(None)
event_chat_func = EventFunc(self.event_chat)
vp.vp_event_set(instance, 0, event_chat_func)
...
def event_chat(self):
print "Hello"
...
event_chat被正确调用并打印“Hello”
但当我用这个的时候
^{pr2}$在聊天室.py公司名称:
from ctypes import CFUNCTYPE
...
class VPSDK:
def __init__(self, vp, instance):
EventFunc = CFUNCTYPE(None)
event_chat_func = EventFunc(self.event_chat)
vp.vp_event_set(instance, 0, event_chat_func)
def event_chat(self):
print "Hello"
...
我得到一个错误“非法指令”
我做错什么了!?我需要使用这个单独的类,否则我的bot的其他部分将失去功能。在
可能必须调用生存期才能维护引用。请参阅Python ctypes documentation中15.16.1.17. Callback functions结尾处的重要注释…。在
一种方法是使用
self.event_chat_func
,在包含对象的生命周期内存储它。在另外,创建
chat.VPSDK(vp, instance)
会创建一个chat.VPSDK
的实例,该实例超出了下一行的范围。第一个示例中没有演示bot
是如何实例化的,但是VPSDK
对象的生存时间并不长。在相关问题 更多 >
编程相关推荐