C++调用python并获取其返回值
先上实例代码:
C++代码:
//初始化py环境
// Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
if(!Py_IsInitialized())
{
printf("cant initialize\n");
return;
}
//导入PY文件
PyObject* pModule = PyImport_ImportModule("nyh");
if (!pModule)
{
printf("cant open py file");
return;
}
else
printf("open py file sucess\n");
//获取PY文件中的函数
PyObject* pFunhello = PyObject_GetAttrString(pModule,"nyhtest");
if(!pFunhello)
{
cout<<"Get function failed"<<endl;
}
PyObject* pArg = NULL;
char* ch;
QByteArray ba = filename.toLatin1();
ch = ba.data(); //Qstring转成char类型
pArg = Py_BuildValue("(s)",ch); //一个字符串参数
PyObject* pyValue = PyObject_CallObject(pFunhello,pArg);
char *imagePath,*IO_door;
PyArg_ParseTuple(pyValue,"s|s",&imagePath,&IO_door);//只返回一个数时会显示乱码,所以加了没有含义的IO_door
if(pyValue)
{
printf("return sucess\n");
//ui->textEdit_5->setText(QString::fromUtf8(imagePath));
//printf(string(imagePath));
QString imgpth=QString::fromUtf8(imagePath);
QImage img;
img.load(imgpth);
ui->label->setPixmap(QPixmap::fromImage(img));
}
printf("Finished\n");
python代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__all__=[ ]
def scenelocation(imagePath):
xx='none'
return 'cam.jpg',xx
注:python中的cam.jpg为同目录下的图片文件名,C++中的filename为前面编写的选择的图片文件名。
首先初始化python环境:
Py_Initialize();
PyRun_SimpleString(“import sys”);
PyRun_SimpleString(“sys.path.append(’./’)”);
这里注释掉Py_Initialize();是因为主函数里已经初始化过了。
然后导入python文件模块:
PyObject* pModule = PyImport_ImportModule(“nyh”); //nyh为py文件名,不需要加.py
然后获取py文件中的函数:
PyObject* pFunhello = PyObject_GetAttrString(pModule,“nyhtest”); //nyhtest为函数名
然后把图片路径作为参数传入给py文件函数模块:
PyObject* pArg = NULL;
char* ch;
QByteArray ba = filename.toLatin1();
ch = ba.data(); //Qstring转成char类型
pArg = Py_BuildValue("(s)",ch); //一个字符串参数
获取py函数的返回值:
PyObject* pyValue = PyObject_CallObject(pFunhello,pArg);
读取返回值:
PyObject* pyValue = PyObject_CallObject(pFunhello,pArg);
char *imagePath,*IO_door;
PyArg_ParseTuple(pyValue,“s|s”,&imagePath,&IO_door);//只返回一个会显示乱码
最后再将获取到的返回值,修改为Qt可以调用的图片路径格式,并显示在label里即可。