Python Ctypes怪异行为

2024-09-24 12:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为一个名为虚拟天堂的应用程序设计一个机器人程序,而用来构建机器人程序的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的其他部分将失去功能。在


Tags: instanceimportself程序eventhellodefchat
1条回答
网友
1楼 · 发布于 2024-09-24 12:29:51

可能必须调用生存期才能维护引用。请参阅Python ctypes documentation15.16.1.17. Callback functions结尾处的重要注释…。在

一种方法是使用self.event_chat_func,在包含对象的生命周期内存储它。在

另外,创建chat.VPSDK(vp, instance)会创建一个chat.VPSDK的实例,该实例超出了下一行的范围。第一个示例中没有演示bot是如何实例化的,但是VPSDK对象的生存时间并不长。在

相关问题 更多 >