2009-04-26 31 views
7

使用PyObjC,有可能導入一個Python模塊,調用一個函數並得到結果作爲(比方說)一個NSString?是否可以從ObjC調用Python模塊?

例如,執行以下Python代碼相當於:

import mymodule 
result = mymodule.mymethod() 

..in僞ObjC:

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

重複:http://stackoverflow.com/questions/49137/calling -python-從-AC-節目換分佈; http://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c。你可以在任何應用程序中嵌入Python。 – 2009-04-26 01:56:47

回答

12

正如亞歷馬爾泰利的答案(雖然在郵件列表中的鏈接被打破,它應該是https://docs.python.org/extending/embedding.html#pure-embedding)提到..調用的C-方式..

print urllib.urlopen("http://google.com").read() 
  • 添加了Python。框架項目(權/System/Library/Frameworks/
  • 單擊External Frameworks..Add > Existing 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

相關問題