cocoa项目中嵌入python

添加链接库:
A5C731A1-10A4-46B3-AF78-A32AB4AF9CA2.png

文件结构:
QQ20130107-1.png

代码

main.m

#import 
#import 

int main(int argc, char *argv[]) {
    Py_Initialize();
    // 这里面自己定义一个hello函数(python的)好了
    PyRun_SimpleString("import hmac, binascii\n"
                       "from itertools import izip, cycle\n");
    int result = NSApplicationMain(argc, (const char **)argv);
    Py_Finalize();
    return result;
}

控制器里面直接使用就好了

- (IBAction)runpy:(id)sender {
    PyObject *m, *f, *a, *k;

    m = PyImport_ImportModule("__main__");
    f = PyObject_GetAttrString(m, "hello");
    a = PyTuple_Pack(1, PyString_FromString([[_email stringValue] UTF8String]));
    k = PyObject_CallObject(f, a);
    
    // NSLog(@"%@", [NSString stringWithUTF8String:PyString_AsString(k)]);
    [_keycode setStringValue:[NSString stringWithUTF8String:PyString_AsString(k)]];
    
    Py_DECREF(k);
    Py_DECREF(a);
    Py_DECREF(f);
    Py_DECREF(m);
}

标签: none

添加新评论