环境 :
win7 + Qt5.9.2 + MinGW32 + py3.6.4 32 bit
Py 下载地址 https://www.python.org/downloads/
注意: py 版本要和你程序编译器版本对应 32bit 对应 32bit 64bit 对应64bit, 否则链接失败
安装好之后我们需要在pro 加入 libs 和 include 路径
1.调用普通函数
#include "mainwindow.h"
#include <QApplication>
#include "Python.h"
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Py_Initialize();
if(!Py_IsInitialized())
{
qDebug()<<"inital error";
return -1;
}
qDebug()<<"inital ok";
PyRun_SimpleString("import sys");
//py 的路径一定要加上 否则下面的 PyObject 为NULL
PyRun_SimpleString("sys.path.append('C:/Users/Administrator/Desktop')");
PyObject* pObj = PyImport_ImportModule("testPy");
if(pObj == NULL)
{
qDebug()<<"PyImport_ImportModule error";
return -1;
}
PyObject* pFunc = PyObject_GetAttrString(pObj,"printHello");
if(pFunc == NULL)
{
qDebug()<<"fun error";
return -1;
}
PyEval_CallObject(pFunc,NULL);
Py_Finalize();
return a.exec();
}
这时候会编译不过,error:error: expected unqualified-id before ‘;’ token
将error展开说是在python中的object.h文件中的slots冲突,
原因:由于QT中定义了slots作为关键了,而python3中有使用slot作为变量,所以有冲突
加上下面的两句, #undef slots #define slots QT_SLOTS
运行成功
2.调用带参函数
PyObject* pFunc = PyObject_GetAttrString(pObj,"printAdd");
if(pFunc == NULL)
{
qDebug()<<"fun error";
return -1;
}
//2个参数
PyObject* pArgs = PyTuple_New(2);
pArgs = Py_BuildValue("(i,i)",2,2);
//(i,i)的意思 "i"(integer) [int] :将一个C类型的int转换成Python int对象
PyEval_CallObject(pFunc,pArgs);
Py_Finalize();
3.调用带返回值函数