代碼如下,分別演示直接執(zhí)行python語句、無返回?zé)o參數(shù)函數(shù)調(diào)用、返回單參數(shù)函數(shù)調(diào)用。返回多參數(shù)函數(shù)調(diào)用:
#include <Python.h>
#include <iostream>
using namespace std;
//執(zhí)行python命令
void ExecPythonCommand()
{
//直接執(zhí)行
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
}
//調(diào)用無參數(shù)函數(shù)
void InvokeNoParm()
{
PyObject* pMod = NULL;
PyObject* pFunc = NULL;
//導(dǎo)入模塊
pMod = PyImport_ImportModule("Life");
if(pMod)
{
//獲取函數(shù)地址
pFunc = PyObject_GetAttrString(pMod, "a");
if(pFunc)
{
//函數(shù)調(diào)用
PyEval_CallObject(pFunc, NULL);
}
else
{
cout << "cannot find function a" << endl;
}
}
else
{
cout << "cannot find Life.py" << endl;
}
}
//調(diào)用一參數(shù)函數(shù)
void InvokeWith1Parm()
{
PyObject* pMod = NULL;
PyObject* pFunc = NULL;
PyObject* pParm = NULL;
PyObject* pRetVal = NULL;
int iRetVal = 0;
//導(dǎo)入模塊
pMod = PyImport_ImportModule("FuncDef");
if(pMod)
{
pFunc = PyObject_GetAttrString(pMod, "square");
if(pFunc)
{
//創(chuàng)建參數(shù)
pParm = Py_BuildValue("(i)", 5);
//函數(shù)調(diào)用
pRetVal = PyEval_CallObject(pFunc, pParm);
//解析返回值
PyArg_Parse(pRetVal, "i", &iRetVal);
cout << "square 5 is: " << iRetVal << endl;
}
else
{
cout << "cannot find function square" << endl;
}
}
else
{
cout << "cannot find FuncDef.py" << endl;
}
}
//調(diào)用多參數(shù)函數(shù)
void InvokeWith2Parm()
{
PyObject* pMod = NULL;
PyObject* pFunc = NULL;
PyObject* pParm = NULL;
PyObject* pRetVal = NULL;
int iRetVal = 0;
//導(dǎo)入模塊
pMod = PyImport_ImportModule("add");
if(pMod)
{
pFunc = PyObject_GetAttrString(pMod, "add");
if(pFunc)
{
//創(chuàng)建兩個(gè)參數(shù)
pParm = PyTuple_New(2);
//為參數(shù)賦值
PyTuple_SetItem(pParm, 0, Py_BuildValue("i",2000));
PyTuple_SetItem(pParm, 1, Py_BuildValue("i",3000));
//函數(shù)調(diào)用
pRetVal = PyEval_CallObject(pFunc, pParm);
//解析返回值
PyArg_Parse(pRetVal, "i", &iRetVal);
cout << "2000 + 3000 = " << iRetVal << endl;
}
else
{
cout << "cannot find function square" << endl;
}
}
else
{
cout << "cannot find add.py" << endl;
}
}
int main(int argc, char* argv[])
{
Py_Initialize(); //python 解釋器的初始化
ExecPythonCommand();
InvokeNoParm();
InvokeWith1Parm();
InvokeWith2Parm();
Py_Finalize(); // 垃圾回收、清除導(dǎo)入庫
return 0;
}
習(xí)慣C++的內(nèi)存分配釋放,突然間不用釋放,感覺很蹊蹺,上網(wǎng)查發(fā)現(xiàn)也沒有釋放函數(shù)。如果真這樣的話,是很可怕的,因?yàn)闊o法自己管理內(nèi)存,但是我相信編譯器作者的垃圾回收機(jī)制,所以O(shè)K,不管!!
代碼下載
posted on 2006-01-17 20:04
EricWong 閱讀(667)
評(píng)論(1) 編輯 收藏 所屬分類:
C&C++