环境搭建
QT调用Python脚本(无参,有参,返回值)和QT5.12安装详细讲解,避坑手册_qt调用python 返回参数-优快云博客
cmath:1136:11: error: '::hypot' has not been declared - 简书
QT添加python解释环境_qt python开发环境-优快云博客
VS2019使用Keras.Net报错:Fatal Python error: initfsencoding: unable to load the file
https://juejin.cn/post/6869216480446283789
QT 调用python 执行到 PyImport_ImportModule("aaa");触发The GDB Process terminal
Qt链接anaconda动态库详细过程_qt anacoda-优快云博客
VS2019调用python
Visual Studio 2019下使用C++与Python进行混合编程——环境配置与C++调用Python API接口_visual studio2019怎么用python交互式开发-优快云博客
VS2019+QT VS Tools+Anaconda Python混编环境搭建
VS2019+QT5.14.2安装及配置编译环境_qt5.14.2 vs2019-优快云博客
测试环境
Anaconda3--python3.8.8
VS2019
QT5.14.2
VS项目设置
QT项目设置
设计师一定True,不然打开设计师界面莫名退出。
下图设置可以同时打开窗口和控制台打印输出。
Python调用逻辑
#include <iostream>
#include <Python.h>
void callMyPython()
{
std::cout << "----------------callMyPython function--------------" << std::endl;
//1.初始化python接口
Py_SetPythonHome(L"D:/ProgramData/anaconda3"); //这一步很重要哈,有可能QT找不到python根目录
Py_Initialize();
if (!Py_IsInitialized)
{
std::cout << "python init failed" << std::endl;
return;
}
//2.导入依赖库
PyRun_SimpleString("import sys");//执行py单条语句
//3.初始化python系统文件路径,以便访问到python源码文件所在的路径
PyRun_SimpleString("sys.path.append('./')");
PyRun_SimpleString("import os");
PyRun_SimpleString("print('hello, python')");
//PyRun_SimpleString("print(os.getcwd())");
//4.调用python源码文件,只写文件名,不用写后缀
PyObject* module = PyImport_ImportModule("call_python");
if (module == nullptr)
{
std::cout << "module not found: call_python" << std::endl;
return;
}
//5.获取python文件里面的函数
PyObject* test = PyObject_GetAttrString(module, "test");
if (!test || !PyCallable_Check(test))
{
std::cout << "function not found: test" << std::endl;
return;
}
//6.调用函数,函数对象与传入参数
PyObject_CallObject(test, nullptr);
PyRun_SimpleString("print(os.getcwd())");
//4.调用python源码文件,只写文件名,不用写后缀
module = PyImport_ImportModule("sample_run");
Py_Finalize();
//std::string str;
//std::cin >> str;
return;
}
void on_pBrunPyhon_clicked()
{
callMyPython();
}
编译调试
DEBUG LNK2019 无法解析的外部符号 __imp__Py_NegativeRefcount,函数 _Py_DECREF 中引用了该符号
这是因为使用的 python 是 Release 版,而编译是在 Debug 模式下编译的(Release 模式下没有此问题)
在 python 的安装位置找到 include
文件夹,在文件夹下找到 pyconfig.h
、object.h
文件
因为我用的是 anaconda3 装的,所以
我的 pyconfig.h
位置为 D:\Programs\anaconda3\include\pyconfig.h
我的 object.h
位置为 D:\Programs\anaconda3\include\object.h
修改 pyconfig.h
注释 # define Py_DEBUG