在PyObjC中使用Python函数回调?

2 投票
1 回答
780 浏览
提问于 2025-04-16 00:50

我正在尝试使用一个用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制作我的库了。

谢谢你的任何帮助。

1 个回答

2

我猜可能是引用计数的问题。

你没有保存你传给addPyFunc_的create_callback()的结果。

所以在你调用它之前,它可能就被垃圾回收了。

撰写回答