Created
September 20, 2012 07:26
-
-
Save andyvanee/3754412 to your computer and use it in GitHub Desktop.
Embed Python in Objective-C (without PyObjC)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def my_func(): | |
return "embedding?" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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