本人由于项目需要,想利用Qt C++控制硬件和采集传感器数据,并利用python进行数据处理,所以先尝试在Qt C++项目里调用python代码。
感谢作者 _东门吹雪 !!
我的开发环境为Visual Studio2019 + Qt5.13.0,python3.8.2
一、python下载及安装
1. 去python官网下载python安装包并安装
python3.8.2下载地址:https://www.python.org/downloads/release/python-382/
下载python的时候,要注意你是32位的Qt就要下载32位的python,64位同理。
安装的时候,注意勾选“到环境变量选项” !!
2. 修改python与Qt的一个冲突
修改python安装路径里的/include/object.h这个文件,在PyType_Spec这个结构体首尾各加一行代码:
#undef slots
typedef struct{
const char* name;
int basicsize;
int itemsize;
unsigned int flags;
PyType_Slot *slots; /* terminated by slot==0. */
} PyType_Spec;
#define slots Q_SLOTS
3. 使用notepad++或者记事本编写一个简单的python程序
将文件保存为“helloworld.py",后面要放在Qt项目的Debug目录下:
def helloWorldFunc():
print("helloworld!")
4. 在Qt中调用 helloworld.py
在Visual Studio里新建一个Qt项目。
更改debug模式下的项目属性:
项目属性 -> 配置属性 -> C/C++ -> 常规 -> 附加包含目录 添加“C:\Python\Python38-32\include”(这个根据实际python安装路径)
项目属性 -> 配置属性 -> 链接器 -> 常规 -> 附加库目录 添加“C:\Python\Python38-32\libs”
项目属性 -> 配置属性 -> 链接器 -> 系统 -> 子系统 修改为 控制台
在 .cpp文件中添加如下代码:
//进行初始化
Py_Initialize();
//如果初始化失败,返回
if(!Py_IsInitialized())
{
qDebug() << "IsInitialized: error";
}
//导入.py文件
PyObject *pModule = PyImport_ImportModule("helloworld");
if(!pModule)
{
qDebug() << "ImportModule: error";
}
//helloWorldFunc
PyObject * pFuncHello = PyObject_GetAttrString(pModule, "helloWorldFunc");
//如果失败则返回
if(!pFuncHello)
{
qDebug() << "GetAttrString: error";
}
//调用函数
PyObject_CallFunction(pFuncHello, NULL);
//退出
Py_Finalize();
先运行一次,解决方案路径下会生成Debug文件夹,里面会有 .exe文件,
然后把C:\Python\Python38-32\下的python3.dll、python38.dll和前面写好的helloworld.py放到Debug文件夹下:
再运行一次,就成功了!
目前只能在debug模式下调用,python38.dll在release模式下会报错。
再次感谢 _东门吹雪 的博客!!