Như đã đề cập trong câu trả lời Alex Martelli của (mặc dù các liên kết trong tin nhắn mailing-list đã bị hỏng, nó phải là https://docs.python.org/extending/embedding.html#pure-embedding) .. Cách C gọi ..
print urllib.urlopen("http://google.com").read()
- Thêm Python. khuôn khổ dự án của bạn (nhấp chuột phải
External Frameworks..
, Add > Existing Frameworks
. Khuôn khổ ở trong /System/Library/Frameworks/
- Thêm
/System/Library/Frameworks/Python.framework/Headers
để bạn "header tìm kiếm Path" (Project > Edit Project Settings
)
Các mã sau đây nên làm việc (mặc dù nó có thể không phải là mã tốt nhất từng được viết ..)
#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];
}
Cũng this tutorial là tốt
trùng lặp: http://stackoverflow.com/questions/49137/calling -python-from-ac-program-for-distribution; http://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c. Bạn có thể nhúng Python vào bất kỳ ứng dụng nào. –
@ S.Lott Đây không phải là bản sao; những câu hỏi đó là về C++, không phải Objective-C. Trong khi bạn có thể sử dụng Objective-C++ để kết hợp C++ và Objective-C, bạn phải tự bọc tất cả mã C++ trong các lớp Objective-C nếu bạn cần sử dụng chúng như các lớp Objective-C. –