步骤
- 包含Python.h,引入python.lib
- Py_Initialize()初始化,结束时调用Py_Finalize()
- 导入sys模块,添加python脚本路径
- 导入脚本文件,从脚本中导入函数模块
- 构造入参,如果有三个参数就构造PyTuple_New(3)
- 构造每一个参数,可以是C++的基本类型,也可以是Python的List类型
- 将所有参数加入到Tuple之中
- 函数调用,得到返回值
- 直接解析C++基本类型的返回值
- 或者使用PyList_GetItem等函数解析嵌套的返回值
C++代码
#include "Python.h"
Py_Initialize();
if ( Py_IsInitialized() )
{
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./pyScript')");
}
PyObject* pModule = PyImport_ImportModule("delaunay");
PyObject* pFunSetSeedPoint= PyObject_GetAttrString(pModule,"setSeedPoint");
PyObject* args = PyTuple_New(2);
PyObject* pReturnValue;
PyObject* pyListX = PyList_New(length);
PyObject* pyListY = PyList_New(length);
for(int i=0; i<length; i++)
{
PyList_SetItem(pyListX, i, PyFloat_FromDouble( seedPoint[i].x() ));
PyList_SetItem(pyListY, i, PyFloat_FromDouble( seedPoint[i].y() ));
}
PyTuple_SetItem(args, 0, pyListX);
PyTuple_SetItem(args, 1, pyListY);
if (pModule && pFunSetSeedPoint)
{
pReturnValue = PyObject_CallObject(pFunSetSeedPoint, args);
if(PyList_Check(pReturnValue ))
{
int SizeOfList = PyList_Size(pReturnValue );
for(int i = 0; i < SizeOfList; i++)
{
PyObject *ListItem = PyList_GetItem(pReturnValue, i);
int NumOfItems = PyList_Size(ListItem);
for(int Index_k = 0; Index_k < NumOfItems; Index_k++)
{
PyObject *Item = PyList_GetItem(ListItem, Index_k);
qDebug() << PyFloat_AsDouble(Item) <<"\n ";
Py_DECREF(Item);
}
Py_DECREF(ListItem);
}
}
else
{
qDebug()<<"something wrong when set seed center in python!";
}
}
Finalize();
Python 代码
def setSeedCenter(x, y):
global seedCenter
count = len(x)
seedPoint = np.resize(seedPoint, (count, 2))
for i in range(len(x)):
seedPoint[i][0] = x[i]
seedPoint[i][1] = y[i]
xx = []
yy = []
for i in range(len(seedPoint)):
xx.append(seedPoint[i][0])
yy.append(seedPoint[i][1])
result.append(xx)
result.append(yy)
return result