2009-04-26 10 views
7

PyObjCを使用すると、Pythonモジュールをインポートし、関数を呼び出して結果をNSStringとして取得できますか?ObjCからPythonモジュールを呼び出すことは可能ですか?

import mymodule 
result = mymodule.mymethod() 

..in擬似にObjC::次のPythonコードの同等やっ例えば

PyModule *mypymod = [PyImport module:@"mymodule"]; 
NSString *result = [[mypymod getattr:"mymethod"] call:@"mymethod"]; 
+0

重複です:http://stackoverflow.com/questions/49137/calling -python-from-ac-program-for-distribution; http://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c。任意のアプリケーションにPythonを組み込むことができます。 –

+2

@ S.Lottこれは複製ではありません。これらの質問はObjective-CではなくC++に関するものです。 Objective-C++を使用してC++とObjective-Cを混在させることはできますが、Objective-Cクラスとして使用する必要がある場合は、Objective-CクラスのすべてのC++コードを自分でラップする必要があります。 –

答えて

12

のPythonを追加

print urllib.urlopen("http://google.com").read() 
  • ..呼び出しのCの方法..(メーリングリストのメッセージ内のリンクが壊れていたものの、それはhttps://docs.python.org/extending/embedding.html#pure-embeddingする必要があります)アレックスマルテッリの答えで述べたように。あなたのプロジェクトへのフレームワーク(右External Frameworks..Add > Existing Frameworksをクリックします。/System/Library/Frameworks/
  • あなたの "ヘッダ検索パス" に/System/Library/Frameworks/Python.framework/Headersを追加(Project > Edit Project Settings
フレームワーク

(それはおそらくこれまでに書かれた最高のコードではありませんが...)次のコードは動作するはずです

#include <Python.h> 

int main(){ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    Py_Initialize(); 

    // import urllib 
    PyObject *mymodule = PyImport_Import(PyString_FromString("urllib")); 
    // thefunc = urllib.urlopen 
    PyObject *thefunc = PyObject_GetAttrString(mymodule, "urlopen"); 

    // if callable(thefunc): 
    if(thefunc && PyCallable_Check(thefunc)){ 
     // theargs =() 
     PyObject *theargs = PyTuple_New(1); 

     // theargs[0] = "http://google.com" 
     PyTuple_SetItem(theargs, 0, PyString_FromString("http://google.com")); 

     // f = thefunc.__call__(*theargs) 
     PyObject *f = PyObject_CallObject(thefunc, theargs); 

     // read = f.read 
     PyObject *read = PyObject_GetAttrString(f, "read"); 

     // result = read.__call__() 
     PyObject *result = PyObject_CallObject(read, NULL); 


     if(result != NULL){ 
      // print result 
      printf("Result of call: %s", PyString_AsString(result)); 
     } 
    } 
    [pool release]; 
} 

またthis tutorial良い

関連する問題