如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033
由于Python简单而强大的功能,如果我们能在C++中集成Python那就太好了。
环境:
Python35:python-3.5.4 32位
QT:5.6.2 32位
编译器:Visual Studio 2013
操作系统:windows 7 64Bit SP1
1.Python的安装
略过
假设安装路径为C:\Python
2.Python头文件和库文件的提取
在路径C:\Python\Python35-32中有include和libs,里面分别是头文件和lib文件,在根目录下有dll文件。
3.在QT中集成Python
3.1 在Pro中增加外部库的路径
注意:路径需要和自己的步骤2中提出的路径相同
unix|win32: LIBS += -L$$PWD/../../thirdBaseLib/Python35/x86/libs/ -lpython35
INCLUDEPATH += $$PWD/../../thirdBaseLib/Python35/include
DEPENDPATH += $$PWD/../../thirdBaseLib/Python35/include
3.2 引入Python.h头文件
#include "Python.h"
3.3 简单的运行Python
hello.py文件内容:
# -*- coding: utf-8 -*-
def hello():
print("hello python!")
3.3.1 初始化Python模块
//初始化python模块
Py_Initialize();
if ( !Py_IsInitialized() )
{
return;
}
3.3.2 设置*.py文件所在的路径
// 将Python工作路径切换到待调用模块所在目录,一定要保证路径名的正确性
PyRun_SimpleString("import sys");
QString setSysPath = QString("sys.path.append('%1')").arg(QCoreApplication::applicationDirPath());
PyRun_SimpleString(setSysPath.toStdString().c_str());
3.3.3 导入hello.py模块
//导入hello.py模块
PyObject* pModule = PyImport_ImportModule("hello");
if (!pModule) {
infoData = "Can not open python file!";
qDebug() << infoData;
return;
}
3.3.4获取hello模块中的hello函数
//获取hello模块中的hello函数
PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello");
if(!pFunhello){
infoData = "Get function hello failed";
qDebug()<< infoData;
return;
}
3.3.5调用hello函数
//调用hello函数
PyObject_CallFunction(pFunhello,NULL);
3.3.6结束,释放python
//结束,释放python
Py_Finalize();
4.运行结果:
觉得文章对你有帮助,可以扫描二维码捐赠给博主,谢谢!
如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:12951803