正如亞歷馬爾泰利的答案(雖然在郵件列表中的鏈接被打破,它應該是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好
來源
2009-04-26 15:45:38
dbr
重複: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