基于Qt5.14的c++/python3.6混合编程环境搭建
自己第一次搭建过程中出了很多问题也参考了很多网站,主要是以下几点:
1.qt pro文件
2.找到python库的路径
3.py文件路径的问题
1.Qt pro配置文件
INCLUDEPATH += /Users/usersname/opt/anaconda2/envs/tensorflowEnvironment/include/python3.6m
LIBS += -L/Users/usersname/opt/anaconda2/envs/tensorflowEnvironment/lib/python3.6/config-3.6m-darwin -lpython3.6m -ldl
CONFIG += no_keywords//解决slot重名的问题
2.把python的lib文件夹放到生成的release/debug文件中
3.py文件的初始化中要加入下面两句话,否则会找不到py文件
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('/Users/usersname/mycode/Qtcode/python_test/')");
4.py文件命名不要用test.py
测试代码:
main.cpp
#include <QCoreApplication>
#include <Python.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Py_Initialize();
if ( !Py_IsInitialized() )
{
cout<< "Cant init\n" << endl;
return -1;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('/Users/yangming/mycode/Qtcode/python_test/')");
PyObject* pModule = PyImport_ImportModule("test_py");
// 这里的test_py就是创建的python文件
if (!pModule) {
cout<< "Cant open python file!\n" << endl;
return -1;
}
PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello");
// 这里的hello就是python文件定义的函数
// PyObject* pDict = PyModule_GetDict(pModule);
// if (!pDict) {
// printf("Cant find dictionary.\n");
// return -1;
// }
// PyObject* pFunhello = PyDict_GetItemString(pDict, "hello");
if(!pFunhello){
cout<<"Get function hello failed"<<endl;
return -1;
}
PyObject_CallFunction(pFunhello,NULL);
Py_Finalize();
return a.exec();
}
test_py.py
# -*- coding: utf-8 -*-
def hello():
print("hello world!")
参考:
https://www.e-learn.cn/content/python/1322577
https://blog.csdn.net/qq_32716885/article/details/80350076
https://blog.csdn.net/liulina603/article/details/79442021