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

转自:http://chensx.iteye.com/blog/1299383

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

Python代码   收藏代码
  1. # filename : cal.py  
  2. # return type : tuple  
  3. def mix(a, b) :  
  4.     r1 = a + b  
  5.     r2 = a - b  
  6.     return (r1, r2) # (7,3)  

C++代码   收藏代码
  1. #include "stdafx.h"  
  2. #include ".\\include\\Python.h"  
  3.   
  4. int _tmain(int argc, _TCHAR* argv[])  
  5. {  
  6.     string filename = "cal"// cal.py  
  7.     string methodname_mix = "mix"// function name  
  8.   
  9.     Py_Initialize();    
  10.   
  11.     // load the module  
  12.     PyObject * pyFileName = PyString_FromString(filename.c_str());  
  13.     PyObject * pyMod = PyImport_Import(pyFileName);   
  14.   
  15.     // load the function  
  16.     PyObject * pyFunc_mix = PyObject_GetAttrString(pyMod, methodname_mix.c_str());  
  17.   
  18.     // test the function is callable  
  19.     if (pyFunc_mix && PyCallable_Check(pyFunc_mix))  
  20.     {  
  21.         PyObject * pyParams = PyTuple_New(2);  
  22.         PyTuple_SetItem(pyParams, 0, Py_BuildValue("i", 5));  
  23.         PyTuple_SetItem(pyParams, 1, Py_BuildValue("i", 2));  
  24.   
  25.         // ok, call the function  
  26.         int r1 = 0, r2 = 0;  
  27.         PyObject * pyValue = PyObject_CallObject(pyFunc_mix, pyParams);           
  28.         PyArg_ParseTuple(pyValue, "i|i", &r1, &r2);  
  29.         if (pyValue)  
  30.         {  
  31.             printf("%d,%d\n", r1, r2); //output is 7,3  
  32.         }         
  33.     }  
  34.   
  35.     Py_Finalize();    
  36.   
  37.     return 0;  
  38. }  


猜你喜欢

转载自blog.csdn.net/manketon/article/details/80318968