【问题标题】:PyObjC and method_exchangeImplementations: crash. correct usage?PyObjC 和 method_exchangeImplementations:崩溃。正确用法?
【发布时间】:2011-09-12 03:32:12
【问题描述】:

我正在使用 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] 中有一些奇怪的回溯。

代码基本正确吗?

有什么问题?

【问题讨论】:

  • BrowserWindowController 是你的课吗?如果是这样,您为什么要将它的实现换成不同的,而不仅仅是在它自己的实现中做您需要做的事情?
  • @Peter:不,它来自另一个我无法更改实现的框架。

标签: objective-c macos cocoa pyobjc objective-c-runtime


【解决方案1】:

啊,当我在def myWindowShouldClose_ 前面添加@objc.signature(BrowserWindowController.windowWillClose_.signature) 时,它不再崩溃了。

所以这只是错误/不匹配的签名。

【讨论】:

    猜你喜欢
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 2015-04-23
    • 2016-01-05
    相关资源
    最近更新 更多