代碼: |
#test function def add(a,b): print "in python function add" print "a = " + str(a) print "b = " + str(b) print "ret = " + str(a+b) return def foo(a): print "in python function foo" print "a = " + str(a) print "ret = " + str(a * a) return |
代碼: |
#include "Python.h" int main(int argc, char** argv) { // 初始化Python //在使用Python系統(tǒng)前,必須使用Py_Initialize對其 //進(jìn)行初始化。它會載入Python的內(nèi)建模塊并添加系統(tǒng)路 //徑到模塊搜索路徑中。這個(gè)函數(shù)沒有返回值,檢查系統(tǒng) //是不是初始化成功需要使用Py_IsInitialized。 Py_Initialize(); // 檢查初始化是不是成功 if ( !Py_IsInitialized() ) { return ⑴; } // 添加當(dāng)前路徑 //把輸入的字符串作為Python代碼直接運(yùn)行,返回0 //表示成功,⑴表示有錯(cuò)。大多時(shí)候毛病都是由于字符串 //中有語法毛病。 PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); PyObject *pName,*pModule,*pDict,*pFunc,*pArgs; // 載入名為pytest的腳本 pName = PyString_FromString("pytest"); pModule = PyImport_Import(pName); if ( !pModule ) { printf("can't find pytest.py"); getchar(); return ⑴; } pDict = PyModule_GetDict(pModule); if ( !pDict ) { return ⑴; } // 找出函數(shù)名為add的函數(shù) pFunc = PyDict_GetItemString(pDict, "add"); if ( !pFunc || !PyCallable_Check(pFunc) ) { printf("can't find function [add]"); getchar(); return ⑴; } // 參數(shù)進(jìn)棧 *pArgs; pArgs = PyTuple_New(2); // PyObject* Py_BuildValue(char *format, ...) // 把C++的變量轉(zhuǎn)換成1個(gè)Python對象。當(dāng)需要從 // C++傳遞變量到Python時(shí),就會使用這個(gè)函數(shù)。此函數(shù) // 有點(diǎn)類似C的printf,但格式不同。經(jīng)常使用的格式有 // s 表示字符串, // i 表示整型變量, // f 表示浮點(diǎn)數(shù), // O 表示1個(gè)Python對象。 PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3)); PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4)); // 調(diào)用Python函數(shù) PyObject_CallObject(pFunc, pArgs); //下面這段是查找函數(shù)foo 并履行foo pFunc = PyDict_GetItemString(pDict, "foo"); if ( !pFunc || !PyCallable_Check(pFunc) ) { printf("can't find function [foo]"); getchar(); return ⑴; } pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",2)); // PyObject_CallObject(pFunc, pArgs); Py_DECREF(pName); Py_DECREF(pArgs); Py_DECREF(pModule); // 關(guān)閉Python Py_Finalize(); return 0; } |
編譯選項(xiàng), 需要手動指定Python 的include 路徑, 和鏈接接路徑,
g++ Python.cpp -o Python -I/usr/include/python2.5 -L/usr/lib/python2.5 -lpython2.5