これを行うために 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 で作成された call メソッドが明らかに存在しないためです。どうすればObjective-Cに存在させることができますか?
コードが機能したとしても役に立たないでしょうが、現時点ではテストのみを行っています。コールバックが機能したら、Python 用のライブラリを作成できるようになります。
助けてくれてありがとう。