基于Qt5.14的c++/python3.6混合编程环境搭建

2 篇文章 0 订阅
2 篇文章 0 订阅

基于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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值