Chinaunix首页 | 论坛 | 博客
  • 博客访问: 475370
  • 博文数量: 133
  • 博客积分: 1235
  • 博客等级: 少尉
  • 技术积分: 1201
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-08 19:59
文章分类

全部博文(133)

文章存档

2023年(12)

2022年(3)

2018年(2)

2017年(4)

2016年(4)

2015年(42)

2014年(1)

2013年(12)

2012年(16)

2011年(36)

2010年(1)

分类: LINUX

2013-12-20 10:46:10

转自:http://www.cppblog.com/API/archive/2013/12/06/204616.html
1.当取多个返回值时,如下:
def mix(a, b) :  
    r1 
= a + b  
    r2 
= a - b  
    
return (r1, r2) # (7,3)

c++代码如下:
#include "python.h"
int _tmain(int argc, _TCHAR* argv[]) 

 
string filename = "cal"// cal.py 
 string methodname_mix = "mix"// function name 
 
 Py_Initialize(); 
 
 
// load the module 
 PyObject * pyFileName = PyString_FromString(filename.c_str()); 
 PyObject 
* pyMod = PyImport_Import(pyFileName); 
 
 
// load the function 
 PyObject * 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
}

2.如果返回一个值时:
import string

def AddMult(a, b):
 c 
= a + b
 
print c
 
return c


c++代码如下: 
PyObject* pModule =NULL;
 PyObject
* pFunc = NULL;
 PyObject
* pArgs = NULL;
 PyObject
* pRet = NULL;

 Py_Initialize();
 
 PyRun_SimpleString(
"import sys");
 PyRun_SimpleString(
"sys.path.append('./')");

 pModule 
= PyImport_ImportModule("httpsend");
 pFunc 
= PyObject_GetAttrString(pModule, "AddMult");
 
 
//pArgs = Py_BuildValue("s, s", "This is ", "a python code");
 
 pArgs 
= Py_BuildValue("ii"12,34);
 
 pRet 
= PyObject_CallObject(pFunc,pArgs);
 
int pyResult=0,pyResult2 = 0;
 
char *str;
 
int argRet = PyArg_Parse(pRet,"i"&pyResult);
 
if (argRet)
 
{
 printf(
"yes!\n");
 }

 
else
 
{
 
//错误
 printf("error!\n");
 }


 
if(pModule)
 Py_DECREF(pModule);
 
if(pFunc)
 Py_DECREF(pFunc);
 
if(pArgs)
 Py_DECREF(pArgs);
 
if(pRet)
 Py_DECREF(pRet);


 
//PyGILState_Ensure();
 Py_Finalize();
阅读(2351) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~