我正在使用PyObjC。 PyObjC没有提供method_exchangeImplementations
的接口,所以我试图通过ctypes使用该函数。我试图从某个窗口控制器类中覆盖windowShouldClose:
。
我的代码:
import objc
BrowserWindowController = objc.lookUpClass("BrowserWindowController")
class BrowserWindowController(objc.Category(BrowserWindowController)):
def myWindowShouldClose_(self, sender):
print "myWindowShouldClose", self, sender
return self.myWindowShouldClose_(sender)
from ctypes import *
capi = pythonapi
# id objc_getClass(const char *name)
capi.objc_getClass.restype = c_void_p
capi.objc_getClass.argtypes = [c_char_p]
# SEL sel_registerName(const char *str)
capi.sel_registerName.restype = c_void_p
capi.sel_registerName.argtypes = [c_char_p]
def capi_get_selector(name):
return c_void_p(capi.sel_registerName(name))
# Method class_getInstanceMethod(Class aClass, SEL aSelector)
# Will also search superclass for implementations.
capi.class_getInstanceMethod.restype = c_void_p
capi.class_getInstanceMethod.argtypes = [c_void_p, c_void_p]
# void method_exchangeImplementations(Method m1, Method m2)
capi.method_exchangeImplementations.restype = None
capi.method_exchangeImplementations.argtypes = [c_void_p, c_void_p]
def hook_into_close():
clazz = capi.objc_getClass("BrowserWindowController")
origClose = capi.class_getInstanceMethod(clazz, capi_get_selector("windowShouldClose:"))
newClose = capi.class_getInstanceMethod(clazz, capi_get_selector("myWindowShouldClose:"))
capi.method_exchangeImplementations(origClose, newClose)
这次崩溃。在[NSWindow _close]
中有一些奇怪的回溯。
代码基本上是对的吗?
有什么问题?
答案 0 :(得分:1)
啊,当我在@objc.signature(BrowserWindowController.windowWillClose_.signature)
前面添加def myWindowShouldClose_
时,它不再崩溃。
所以它只是错误/不匹配的签名。