正如 Alex Martelli 的回答中提到的(虽然邮件列表消息中的链接已损坏,但应该是https://docs.python.org/extending/embedding.html#pure-embedding).. C 调用方式。 .
print urllib.urlopen("http://google.com").read()
- 将 Python.framework 添加到您的项目中(右键单击
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];
}
这个教程也不错