2010-12-22 2 views
1

나는 Virtual Paradise라는 응용 프로그램을위한 봇을 설계하려고하는데, 봇을 빌드하기 위해 주어진 SDK가 공유 라이브러리로 컴파일되므로 ctypes를 사용해야합니다. 내가Python Ctypes weird behavior

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를 사용

는 및 인쇄 "안녕하세요"

제대로 호출하지만 도착 나는이

import threading 
import chat 
... 
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() 
     ... 
     chat.VPSDK(vp, instance) 
     ... 

Chat.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" 
     ... 

나도 알아. ror "잘못된 명령"

내가 뭘 잘못하고있다!? 이 별도의 클래스를 사용해야합니다, 그렇지 않으면 내 봇의 다른 부분이 느슨한 기능을합니다.

답변

3

랩핑 된 함수에 대한 참조가 유지 될 수 있도록 유지해야합니다. 중요 사항 ... 15.16.1.17. Callback functions의 끝에Python ctypes documentation에 표시하십시오.

대신에 self.event_chat_func을 사용하여 포함 된 개체의 수명 동안 저장하는 것이 좋습니다.

또한 chat.VPSDK(vp, instance)을 만들면 다음 줄의 범위를 벗어나는 chat.VPSDK의 인스턴스가 만들어집니다. 첫 번째 예제에서는 bot이 인스턴스화 된 방법을 보여주지 않지만 VPSDK 개체는 오래 살아 있지 않습니다.

+0

감사합니다. 방금 "event_chat_func"변수를 "chat.py"내에서 전역 변수로 만들었으며 이제는 문제없이 작동합니다. – MetaDark