Python是一種簡(jiǎn)單易學(xué),功能強(qiáng)大的解釋型編程語(yǔ)言,它有簡(jiǎn)潔明了的語(yǔ)法,高效率的高層數(shù)據(jù)結(jié)構(gòu),,能夠簡(jiǎn)單而有效地實(shí)現(xiàn)面向?qū)ο缶幊蹋貏e適用于快速應(yīng)用程序開(kāi)發(fā),,也可以用來(lái)開(kāi)發(fā)大規(guī)模的重要的商業(yè)應(yīng)用,。Python是一個(gè)理想的腳本語(yǔ)言。
常用的Python/C API介紹 char *cstr; PyObject *pstr, *pmod, *pdict; PyObject *pfunc, *pargs;1. void Py_Initialize( ) 初始化Python解釋器,,在C++程序中使用其它Python/C API之前,必須調(diào)用此函數(shù),,如果調(diào)用失敗,,將產(chǎn)生一個(gè)致命的錯(cuò)誤。例: Py_Initialize();2. int PyRun_SimpleString( const char *command) 執(zhí)行一段Python代碼,,就好象是在__main__ 函數(shù)里面執(zhí)行一樣,。例: PyRun_SimpleString("from time import time,ctime\n" "print ''Today is'',ctime(time())\n");3. PyObject* PyImport_ImportModule( char *name) 導(dǎo)入一個(gè)Python模塊,參數(shù)name可以是*.py文件的文件名,。相當(dāng)于Python內(nèi)建函數(shù)__import__(),。例: pmod = PyImport_ImportModule("mymod"); //mymod.py4. PyObject* PyModule_GetDict( PyObject *module) 相當(dāng)于Python模塊對(duì)象的__dict__ 屬性,得到模塊名稱空間下的字典對(duì)象,。例: pdict = PyModule_GetDict(pmod);5. PyObject* PyRun_String( const char *str, int start, PyObject *globals, PyObject *locals) 執(zhí)行一段Python代碼,。 pstr = PyRun_String("message", Py_eval_input, pdict, pdict);6. int PyArg_Parse( PyObject *args, char *format, ...) 解構(gòu)Python數(shù)據(jù)為C的類型,這樣C程序中才可以使用Python里的數(shù)據(jù),。例: /* convert to C and print it*/ PyArg_Parse(pstr, "s", &cstr); printf("%s\n", cstr);7. PyObject* PyObject_GetAttrString( PyObject *o, char *attr_name) 返回模塊對(duì)象o中的attr_name 屬性或函數(shù),,相當(dāng)于Python中表達(dá)式語(yǔ)句:o.attr_name。例: /* to call mymod.transform(mymod.message) */ pfunc = PyObject_GetAttrString(pmod, "transform");8. PyObject* Py_BuildValue( char *format, ...) 構(gòu)建一個(gè)參數(shù)列表,,把C類型轉(zhuǎn)換為Python對(duì)象,,使Python可以使用C類型數(shù)據(jù),例: cstr="this is hjs''s test, to uppercase"; pargs = Py_BuildValue("(s)", cstr);9. PyEval_CallObject(PyObject* pfunc, PyObject* pargs) 此函數(shù)有兩個(gè)參數(shù),,都指向Python對(duì)象指針,,pfunc是要調(diào)用的Python 函數(shù),通??捎肞yObject_GetAttrString()獲得,;pargs是函數(shù)的參數(shù)列表,通??捎肞y_BuildValue()構(gòu)建,。例: pstr = PyEval_CallObject(pfunc, pargs); PyArg_Parse(pstr, "s", &cstr); printf("%s\n", cstr);10. void Py_Finalize( ) 關(guān)閉Python解釋器,釋放解釋器所占用的資源,。例: Py_Finalize(); Python2.4環(huán)境沒(méi)有提供調(diào)試版本的Python24d.lib,,所以上述示例在release模式下編譯。編譯完成后,,把可行文件和附2給出的mymod.py文件放在一起,再點(diǎn)擊即可運(yùn)行,。為了簡(jiǎn)化編程,,附3 給出了simplepy.h。這樣,調(diào)用mymod.transform變成如下形式: //#include”simplepy.h” CSimplepy py; py.ImportModule("mymod"); std::string str=py.CallObject("transform", "this is hjs''s test, to uppercase"); printf("%s\n", str.c_str()); 接下來(lái),,我們來(lái)用C++為Python編寫(xiě)擴(kuò)展模塊(動(dòng)態(tài)鏈接庫(kù)),,并在Python程序中調(diào)用C++開(kāi)發(fā)的擴(kuò)展功能函數(shù)。生成一個(gè)取名為pyUtil的Win32 DLL工程,,除了pyUtil.cpp文件以外,,從工程中移除所有其它文件,并填入如下的代碼: // pyUtil.cpp #ifdef PYUTIL_EXPORTS #define PYUTIL_API __declspec(dllexport) #else #define PYUTIL_API __declspec(dllimport) #endif #include<windows.h> #include<string> #include<Python.h> BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ?) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } std::string Recognise_Img(const std::string url) { //返回結(jié)果 return "從dll中返回的數(shù)據(jù)... : " +url; } static PyObject* Recognise(PyObject *self, PyObject *args) { const char *url; std::string sts; if (!PyArg_ParseTuple(args, "s", &url)) return NULL; sts = Recognise_Img(url); return Py_BuildValue("s", sts.c_str() ); } static PyMethodDef AllMyMethods[] = { {"Recognise", Recognise, METH_VARARGS},//暴露給Python的函數(shù) {NULL, NULL} /* Sentinel */ }; extern "C" PYUTIL_API void initpyUtil() { PyObject *m, *d; m = Py_InitModule("pyUtil", AllMyMethods); //初始化本模塊,,并暴露函數(shù) d = PyModule_GetDict(m); }在Python代碼中調(diào)用這個(gè)動(dòng)態(tài)鏈接庫(kù): import pyUtil result = pyUtil.Recognise("input url of specific data") print "the result is: "+ result用C++為Python寫(xiě)擴(kuò)展時(shí),,如果您愿意使用Boost.Python庫(kù)的話,開(kāi)發(fā)過(guò)程會(huì)變得更開(kāi)心J,,要編寫(xiě)一個(gè)與上述pyUtil同樣功能的動(dòng)態(tài) 鏈接庫(kù),,只需把文件內(nèi)容替換為下面的代碼。當(dāng)然,,編譯需要boost_python.lib支持,,運(yùn)行需要boost_python.dll支持。 #include<string> #include <boost/python.hpp> using namespace boost::python; #pragma comment(lib, "boost_python.lib") std::string strtmp; char const* Recognise(const char* url) { strtmp ="從dll中返回的數(shù)據(jù)... : "; strtmp+=url; return strtmp.c_str(); } BOOST_PYTHON_MODULE(pyUtil) { def("Recognise", Recognise); }所有示例都在Microsoft Windows XP Professional + Microsoft Visual Studio .NET 2003 + Python2.4環(huán)境下測(cè)試通過(guò),,本文所用的Boost庫(kù)為1.33版本,。 參考資料
附1 text.txt this is test text in text.txt. 附2 mymod.py import string message = ''original string'' message =message+message msg_error="" try: text_file = open("text.txt", "r") whole_thing = text_file.read() print whole_thing text_file.close() except IOError, (errno, strerror): print "I/O error(%s): %s" % (errno, strerror) def transform(input): #input = string.replace(input, ''life'', ''Python'') return string.upper(input) def change_msg(nul): global message #如果沒(méi)有此行,,message是函數(shù)里頭的局部變量 message=''string changed'' return message def r_file(nul): return whole_thing def get_msg(nul): return message 附3 simplepy.h #ifndef _SIMPLEPY_H_ #define _SIMPLEPY_H_ // simplepy.h v1.0 // Purpose: facilities for Embedded Python. // by hujinshan @2005年9月2日9:13:02 #include |
|