mac中xcode 项目中嵌入python
网上很多文章介绍c/c++项目中嵌入python做为脚本都是基于windows环境下VC++的方式,本文向大家讲解如何在mac环境下为xcode的objc项目嵌入python。
1. 首先确保你的系统中已经安装了python3.x,本文使用的python版本为3.7
2. 打开xcode 新建一个Cocoa App项目

3. 设置项目的python包含路径,打开终端,在终端中运行命令 python3-config --cflags

如图所示python头文件的包含路径为 /Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m 在项目的头文件路径中设置为该路径

4. 设置项目的python库路径, 在终端输入命令 python3-config --ldflags

如图所示python 的文件存放在 /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/config-3.7m-darwin 目录下,需要链接的库为-lpython3.7m
我们来设置项目的库文件路径和需要链接的库


项目将静态库 libpython3.7m.a 编译进项目,这样即使运行app的mac电脑上没有安装python环境也不会影响使用。
5. 我们在项目中新建一个目录来存放python文件,并在该目录下放置一个pyhton脚本文件embed_python.py, 项目结构如下

embed_python.py 的内容如下
# -*- coding: utf-8 -*-
def hello():
print('this is embed test!!!')
6. 我们在AppDelegate.m文件添加代码来运行上面脚本中的函数
首先需要包含python头文件
#include <Python.h>
然后在applicationDidFinishLaunching方法中添加下面的代码
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
Py_Initialize(); //初始化python解释器
PyRun_SimpleString("import sys"); //调用python代码
NSString* path = [[NSBundle mainBundle] bundlePath];
NSLog(@"path:%@", path); //app路径
NSString* resPath = [path stringByAppendingString:@"/Contents/Resources"]; //Resources 路径
NSString* localPythonPath = [NSString stringWithFormat:@"sys.path.append('%@')", resPath];
PyRun_SimpleString([localPythonPath cStringUsingEncoding:NSUTF8StringEncoding]); //将Resources目录添加到python路径这样才能调用项目中的python脚本
PyObject *pModule = PyImport_ImportModule("embed_python"); //加载自己编写的python模块,这里是embed_python.py
if (NULL == pModule) {
NSLog(@"pModule is NULL");
}
//加载模块中的方法
PyObject* pMethod = PyObject_GetAttrString(pModule, "hello");
//调用方法
PyObject* pResult = PyObject_CallFunction(pMethod, NULL);
//PyObject* pResult = PyObject_CallObject(pMethod, NULL);
Py_XDECREF(pMethod);
Py_XDECREF(pModule);
Py_XDECREF(pResult);
Py_Finalize();
}
注意:python3中 PyString_FromString() 已经废弃了,如果想要将c的字符串转换为python的字符串需要调用PyUnicode_FromString()方法
PyObject* pNameModule = PyUnicode_FromString("embed_python");
7. 现在让我们编译并运行项目会在log窗口中输出 this is embed test!!!


浙公网安备 33010602011771号