C++与Python的混合编程-调用有参函数以及C++数据类型与Python数据类型间的转换

来源:互联网 发布:mab软件是什么意思 编辑:程序博客网 时间:2024/05/18 20:12

    上一篇讲到PythonnC++的混合编程时,我们使用的C++来调用的是Python的无参函数。那么我们在这里进一步,涉及到有参函数。那么我们就需要将C++的类型转换到Python的数据类型。这里我们需要PyObject*Py_BuildValue(constchar *format, ...)函数。

Python代码:

def Hello(valuestr):    print "Hello," + valuestr

C++代码:

void PyDemo_2(){PyObject * pModule = NULL;PyObject * pFunc = NULL;PyObject * pArg = NULL;pModule = PyImport_ImportModule("demo2");pFunc = PyObject_GetAttrString(pModule, "Hello");pArg = Py_BuildValue("(s)", "heacewalker");PyEval_CallObject(pFunc, pArg);}

    示例程序中Py_BuildValue("(s)","heacewalker"),其中”(s)”是参数类型,”heacewalker”是给予参数的值。

    下面列出了一些Py_BuildValue()的使用方式,具体的format格式使用可以查询Python的帮助文档。

   Py_BuildValue("")       None       Py_BuildValue("i",1)   1   Py_BuildValue("ii",1,2)       (1,2)   Py_BuildValue("()")  ()   Py_BuildValue("(i)",1)  (1)   Py_BuildValue("(ii)",1,2)  (1,2)   Py_BuildValue("(i,i)",1,2)      (1,2)

    最后关于这个函数PyEval_CallObject(pFunc,pArg)其中上一篇无参函数pArg参数位置是NULL

    接下来这里贴出关于两个参数的函数的相关PythonC++代码。

Python代码:

def Addition(fst_val, snd_val):    return fst_val + snd_val

C++代码:

void PyDemo_1(){PyObject * pModule = NULL;PyObject * pFunc = NULL;PyObject * pArg = NULL;PyObject * pAns = NULL;int first_value = 0;int second_value = 0;cout<<"Please enter two integer number:";cin>>first_value>>second_value;pModule = PyImport_ImportModule("demo1");pFunc = PyObject_GetAttrString(pModule, "Addition");pArg = Py_BuildValue("ii", first_value, second_value);pAns = PyEval_CallObject(pFunc,pArg);int answer = 0;PyArg_Parse(pAns, "i", &answer);cout<<"The addition of these two number is "<<answer;}

    这里Python函数最终会返回两个数的和,我们需要将这个值给整型变量answer,所以这里会引发另一个问题,就是将Python类型转换到C++类型,需要使用该函数intPyArg_Parse(PyOject *args, const char *format, ...)具体使用可以查看Python的帮助文档,其中args是需要转换的Python的数据对象,而format部分是与Py_BuildValue函数中的一样。