2024-09-20 04:15:19 发布
网友
我想在ios上运行一个python脚本。 我不想用Python编写整个应用程序,只是其中的一小部分。
我试着去理解PyObjC,但不是那么容易。
你能给我举个例子吗?我想将以下方法的结果保存在NSString变量中。
NSString
def doSomething(): someInfos = "test" return someInfos
下面是调用myModule中定义的函数的示例。模棱两可的python是:
myModule
import myModule pValue = myModule.doSomething() print pValue
在目标c中:
#include <Python.h> - (void)example { PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; NSString *nsString; // Initialize the Python Interpreter Py_Initialize(); // Build the name object pName = PyString_FromString("myModule"); // Load the module object pModule = PyImport_Import(pName); // pDict is a borrowed reference pDict = PyModule_GetDict(pModule); // pFunc is also a borrowed reference pFunc = PyDict_GetItemString(pDict, "doSomething"); if (PyCallable_Check(pFunc)) { pValue = PyObject_CallObject(pFunc, NULL); if (pValue != NULL) { if (PyObject_IsInstance(pValue, (PyObject *)&PyUnicode_Type)) { nsString = [NSString stringWithCharacters:((PyUnicodeObject *)pValue)->str length:((PyUnicodeObject *) pValue)->length]; } else if (PyObject_IsInstance(pValue, (PyObject *)&PyBytes_Type)) { nsString = [NSString stringWithUTF8String:((PyBytesObject *)pValue)->ob_sval]; } else { /* Handle a return value that is neither a PyUnicode_Type nor a PyBytes_Type */ } Py_XDECREF(pValue); } else { PyErr_Print(); } } else { PyErr_Print(); } // Clean up Py_XDECREF(pModule); Py_XDECREF(pName); // Finish the Python Interpreter Py_Finalize(); NSLog(@"%@", nsString); }
有关更多文档,请查看:Extending and Embedding the Python Interpreter
下面是调用
myModule
中定义的函数的示例。模棱两可的python是:在目标c中:
有关更多文档,请查看:Extending and Embedding the Python Interpreter
相关问题 更多 >
编程相关推荐