代碼如下,分別演示直接執行python語句、無返回無參數函數調用、返回單參數函數調用。返回多參數函數調用:
#include <Python.h>
#include <iostream>
using namespace std;
//執行python命令
void ExecPythonCommand()
{
//直接執行
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
}
//調用無參數函數
void InvokeNoParm()
{
PyObject* pMod = NULL;
PyObject* pFunc = NULL;
//導入模塊
pMod = PyImport_ImportModule("Life");
if(pMod)
{
//獲取函數地址
pFunc = PyObject_GetAttrString(pMod, "a");
if(pFunc)
{
//函數調用
PyEval_CallObject(pFunc, NULL);
}
else
{
cout << "cannot find function a" << endl;
}
}
else
{
cout << "cannot find Life.py" << endl;
}
}
//調用一參數函數
void InvokeWith1Parm()
{
PyObject* pMod = NULL;
PyObject* pFunc = NULL;
PyObject* pParm = NULL;
PyObject* pRetVal = NULL;
int iRetVal = 0;
//導入模塊
pMod = PyImport_ImportModule("FuncDef");
if(pMod)
{
pFunc = PyObject_GetAttrString(pMod, "square");
if(pFunc)
{
//創建參數
pParm = Py_BuildValue("(i)", 5);
//函數調用
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;
}
}
//調用多參數函數
void InvokeWith2Parm()
{
PyObject* pMod = NULL;
PyObject* pFunc = NULL;
PyObject* pParm = NULL;
PyObject* pRetVal = NULL;
int iRetVal = 0;
//導入模塊
pMod = PyImport_ImportModule("add");
if(pMod)
{
pFunc = PyObject_GetAttrString(pMod, "add");
if(pFunc)
{
//創建兩個參數
pParm = PyTuple_New(2);
//為參數賦值
PyTuple_SetItem(pParm, 0, Py_BuildValue("i",2000));
PyTuple_SetItem(pParm, 1, Py_BuildValue("i",3000));
//函數調用
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(); // 垃圾回收、清除導入庫
return 0;
}
習慣C++的內存分配釋放,突然間不用釋放,感覺很蹊蹺,上網查發現也沒有釋放函數。如果真這樣的話,是很可怕的,因為無法自己管理內存,但是我相信編譯器作者的垃圾回收機制,所以OK,不管!!
代碼下載
posted on 2005-12-31 18:49
萬連文 閱讀(1944)
評論(0) 編輯 收藏 引用 所屬分類:
亂七八糟