首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++调用回来多个值的Python函数

2012-12-28 
C++调用返回多个值的Python函数某些时候,用python模块来实现一些特定的功能会比用其他类型的模块更加简洁

C++调用返回多个值的Python函数
      某些时候,用python模块来实现一些特定的功能会比用其他类型的模块更加简洁方便。
在C++程序中,调用python模块时需要加载一些必要的libs,这些libs在网上都可以找到。下面的代码演示了C++程序如何调用python中的函数,并得到从python函数中返回的多个值。

#include "stdafx.h"#include ".\\include\\Python.h"int _tmain(int argc, _TCHAR* argv[]){string filename = "cal"; // cal.pystring methodname_mix = "mix"; // function namePy_Initialize();  // load the modulePyObject * pyFileName = PyString_FromString(filename.c_str());PyObject * pyMod = PyImport_Import(pyFileName); // load the functionPyObject * pyFunc_mix = PyObject_GetAttrString(pyMod, methodname_mix.c_str());// test the function is callable    if (pyFunc_mix && PyCallable_Check(pyFunc_mix)){PyObject * pyParams = PyTuple_New(2);PyTuple_SetItem(pyParams, 0, Py_BuildValue("i", 5));PyTuple_SetItem(pyParams, 1, Py_BuildValue("i", 2));// ok, call the function        int r1 = 0, r2 = 0;PyObject * pyValue = PyObject_CallObject(pyFunc_mix, pyParams);PyArg_ParseTuple(pyValue, "i|i", &r1, &r2);if (pyValue){printf("%d,%d\n", r1, r2); //output is 7,3}}Py_Finalize();  return 0;}

热点排行