dbr*_*dbr 8 python pyobjc objective-c
使用PyObjC,是否可以导入Python模块,调用函数并获得结果(例如)NSString?
例如,执行以下Python代码的等效操作:
import mymodule
result = mymodule.mymethod()
Run Code Online (Sandbox Code Playgroud)
..in伪ObjC:
PyModule *mypymod = [PyImport module:@"mymodule"];
NSString *result = [[mypymod getattr:"mymethod"] call:@"mymethod"];
Run Code Online (Sandbox Code Playgroud)
dbr*_*dbr 13
正如Alex Martelli的回答中提到的那样(虽然邮件列表信息中的链接被破坏了,但它应该是https://docs.python.org/extending/embedding.html#pure-embedding).C的呼叫方式. .
print urllib.urlopen("http://google.com").read()
Run Code Online (Sandbox Code Playgroud)
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];
}
Run Code Online (Sandbox Code Playgroud)
此外本教程是好的