c++调用python原理_C++调用返回多个值的Python函数

# filename : cal.py

# return type : tuple

def mix(a, b) :

r1 = a + b

r2 = a - b

return (r1, r2) # (7,3)

#include "stdafx.h"

#include ".\\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

0

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2011-12-08 21:35

浏览 6756

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值