Skip to content

Instantly share code, notes, and snippets.

@andyvanee
Created September 20, 2012 07:26
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andyvanee/3754412 to your computer and use it in GitHub Desktop.
Save andyvanee/3754412 to your computer and use it in GitHub Desktop.
Embed Python in Objective-C (without PyObjC)
def my_func():
return "embedding?"
#import <Python/Python.h> //include the python framework in the project
// ...
-(id)init{
// Embedding me some python, equivalent python in comments
Py_Initialize();
NSLog(@"PyInit");
const char *pypath = [[[NSBundle mainBundle] resourcePath] UTF8String];
// import sys
PyObject *sys = PyImport_Import(PyString_FromString("sys"));
// sys.path.append(resourcePath)
PyObject *sys_path_append = PyObject_GetAttrString(PyObject_GetAttrString(sys, "path"), "append");
PyObject *resourcePath = PyTuple_New(1);
PyTuple_SetItem(resourcePath, 0, PyString_FromString(pypath));
PyObject_CallObject(sys_path_append, resourcePath);
// import MyModule # this is in my project folder
PyObject *myModule = PyImport_Import(PyString_FromString("MyModule"));
// MyModule.my_func()
PyObject *my_func = PyObject_GetAttrString(myModule, "my_func");
if (my_func && PyCallable_Check(my_func)){
PyObject *result = PyObject_CallObject(my_func, NULL);
if(result != NULL){
NSLog(@"Result of call: %s", PyString_AsString(result));
}
}
return [super init];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment