Python是一种简单易学,功能强大的解释型编程语言,它有简洁明了的语法,高效率的高层数据结构,能够简单而有效地实现面向对象编程,特别适用于快速应用程序开发,也可以用来开发大规模的重要的商业应用。Python是一个理想的脚本语言。
常用的Python/C API介绍 char *cstr; PyObject *pstr, *pmod, *pdict; PyObject *pfunc, *pargs;1. void Py_Initialize( ) 初始化Python解释器,在C++程序中使用其它Python/C API之前,必须调用此函数,如果调用失败,将产生一个致命的错误。例: Py_Initialize();2. int PyRun_SimpleString( const char *command) 执行一段Python代码,就好象是在__main__ 函数里面执行一样。例: PyRun_SimpleString("from time import time,ctime\n" "print ''Today is'',ctime(time())\n");3. PyObject* PyImport_ImportModule( char *name) 导入一个Python模块,参数name可以是*.py文件的文件名。相当于Python内建函数__import__()。例: pmod = PyImport_ImportModule("mymod"); //mymod.py4. PyObject* PyModule_GetDict( PyObject *module) 相当于Python模块对象的__dict__ 属性,得到模块名称空间下的字典对象。例: pdict = PyModule_GetDict(pmod);5. PyObject* PyRun_String( const char *str, int start, PyObject *globals, PyObject *locals) 执行一段Python代码。 pstr = PyRun_String("message", Py_eval_input, pdict, pdict);6. int PyArg_Parse( PyObject *args, char *format, ...) 解构Python数据为C的类型,这样C程序中才可以使用Python里的数据。例: /* convert to C and print it*/ PyArg_Parse(pstr, "s", &cstr); printf("%s\n", cstr);7. PyObject* PyObject_GetAttrString( PyObject *o, char *attr_name) 返回模块对象o中的attr_name 属性或函数,相当于Python中表达式语句:o.attr_name。例: /* to call mymod.transform(mymod.message) */ pfunc = PyObject_GetAttrString(pmod, "transform");8. PyObject* Py_BuildValue( char *format, ...) 构建一个参数列表,把C类型转换为Python对象,使Python可以使用C类型数据,例: cstr="this is hjs''s test, to uppercase"; pargs = Py_BuildValue("(s)", cstr);9. PyEval_CallObject(PyObject* pfunc, PyObject* pargs) 此函数有两个参数,都指向Python对象指针,pfunc是要调用的Python 函数,通常可用PyObject_GetAttrString()获得;pargs是函数的参数列表,通常可用Py_BuildValue()构建。例: pstr = PyEval_CallObject(pfunc, pargs); PyArg_Parse(pstr, "s", &cstr); printf("%s\n", cstr);10. void Py_Finalize( ) 关闭Python解释器,释放解释器所占用的资源。例: Py_Finalize(); Python2.4环境没有提供调试版本的Python24d.lib,所以上述示例在release模式下编译。编译完成后,把可行文件和附2给出的mymod.py文件放在一起,再点击即可运行。为了简化编程,附3 给出了simplepy.h。这样,调用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()); 接下来,我们来用C++为Python编写扩展模块(动态链接库),并在Python程序中调用C++开发的扩展功能函数。生成一个取名为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) { //返回结果 return "从dll中返回的数据... : " +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的函数 {NULL, NULL} /* Sentinel */ }; extern "C" PYUTIL_API void initpyUtil() { PyObject *m, *d; m = Py_InitModule("pyUtil", AllMyMethods); //初始化本模块,并暴露函数 d = PyModule_GetDict(m); }在Python代码中调用这个动态链接库: import pyUtil result = pyUtil.Recognise("input url of specific data") print "the result is: "+ result用C++为Python写扩展时,如果您愿意使用Boost.Python库的话,开发过程会变得更开心J,要编写一个与上述pyUtil同样功能的动态 链接库,只需把文件内容替换为下面的代码。当然,编译需要boost_python.lib支持,运行需要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中返回的数据... : "; strtmp+=url; return strtmp.c_str(); } BOOST_PYTHON_MODULE(pyUtil) { def("Recognise", Recognise); }所有示例都在Microsoft Windows XP Professional + Microsoft Visual Studio .NET 2003 + Python2.4环境下测试通过,本文所用的Boost库为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 #如果没有此行,message是函数里头的局部变量 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 |
|