【问题标题】:Using python function callbacks with PyObjC?在 PyObjC 中使用 python 函数回调?
【发布时间】:2010-07-05 14:46:22
【问题描述】:

我正在尝试使用 Python 制作的 Objective-C 类来执行此操作,但 Objective-C 无法调用调用 python 函数的方法。

这是 Objective-C 代码的框架代码:

//
//  scalelib.h
//  Scalelib Cocoa Framework
//
//  Created by Matthew Mitchell on 04/07/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import <Cocoa/Cocoa.h>


@interface Game : NSObject {
    id current_pyfunc;
}
-(void) addPyFunc: (id) pyfunc;
-(void) callPyFunc;
@end

//
//  scalelib.m
//  Scalelib Cocoa Framework
//
//  Created by Matthew Mitchell on 04/07/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "Game.h"


@implementation Game
-(void) addPyFunc: (id) pyfunc{
    current_pyfunc = pyfunc;
}
-(void) callPyFunc{
    [current_pyfunc call]; //Segmentation fault. Method doesn't exist for some reason.
}
@end

这是加载框架并测试回调使用失败的python脚本。

#!/usr/bin/env python2.3
from objc import *
import os,sys
loadBundle("Scalelib Cocoa Framework",globals(),os.path.dirname(sys.argv[0]) + "/Scalelib Cocoa Framework/build/Release/Scalelib Cocoa Framework.framework/")
class PythonCallback(NSObject):
    def setCallback_withArgs_(self, python_function,args): #Python initialisation of class, add the callback function and arguments
        self.python_function = python_function
        self.args = args
        return self
    def call(self): #Used by Objective-C to call python function
        self.python_function(*self.args)
def create_callback(function,args):
    return PythonCallback.alloc().init().setCallback_withArgs_(function,args)
def square(num):
    print num**2
instance = Game.alloc().init()
callback = create_callback(square,[3])
callback.call()
instance.addPyFunc_(create_callback(square,[5]))
instance.callPyFunc()

我得到了输出:

9 分段错误

分段错误是因为python中的调用方法明显不存在。那么如何让它存在于 Objective-C 中呢?

即使代码确实有效,它也是无用的,但我目前只是在测试。一旦我的回调工作正常,我就可以为 python 创建我的库了。

感谢您的帮助。

【问题讨论】:

    标签: python objective-c cocoa segmentation-fault pyobjc


    【解决方案1】:

    我的猜测是保留计数。

    您不会保留传递给 addPyFunc_ 的 create_callback() 的结果

    因此,它可能会在您调用它之前将垃圾收集掉。

    【讨论】:

    • 非常感谢。这样可行。 :D 在通话之前它在哪里以及为什么会被删除?
    • instance.addPyFunc_(create_callback(square,[5])) 执行如下:评估平方(增加它的引用计数)。评估 [5] (创建临时对象,refcount=1) 。将这些参数传递给 create_callback,返回一个对象。减少 [5] 的 python 保留计数。递减 python 保留 square 的计数。将结果对象传递给 addPyFunc 。减少 python 保留对象的计数。它现在为零,所以垃圾收集它。请注意,它是 Python 垃圾收集,而不是 Cocoa。
    猜你喜欢
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多