2009-04-26 27 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

相关问题