Python是一种简单易学,功能强大的解释型编程语言,它有简洁明了的语法,高效率的高层数据结构,可以简单而有效地实现面向对象编程,特别适用于快速应用程序开发,也能够用来开发大规模的重要的商业应用。Python是一个理想的脚本语言。python
Python免费开源,可移植到多种操做系统,只要避免使用依赖于特定操做系统的特性,Python程序无需修改就能够在各类平台上面运行。数据库
Python拥有现代编程语言所具备的一切强大功能,Python标准库十分庞大,能够帮助开发者处理各类工做,如:图形用户界面、文件处理、多媒体、正 则表达式、文档生成、单元测试、线程、数据库、网络通信、网页浏览器、CGI、FTP、电子邮件、XML、HTML、WAV文件、密码系统、Tk和其余与 系统有关的操做。只要安装了Python,这些功能都是可用的除了标准库之外,还有许多其余高质量的库,如wxPython、Twisted和 Python图形库等等数不胜数。编程
Python容易扩展和嵌入。Python提供的许多标准模块支持C或者C++接口。Python和C能够一块儿工做,它能够嵌入到C或者C++的应用程序 当中,所以可用Python语言为应用程序提供脚本接口,因为支持跨语言开发,可用Python设计概念化应用程序,并逐步移植到C,使用前没必要用C重写 应用程序。(Jython使Python能够和Java一块儿工做,使开发者能够在Python里面调Java的包,也能够在Java里面使用Python 的对象。还有更妙的,因为Jython的解释器彻底用Java编写,所以能够在支持Java的任何平台上部署Python程序,甚至WEB浏览器也能够直 接运行Python脚本。)windows
提出问题 浏览器
在某个C++应用程序中,咱们用一组插件来实现一些具备统一接口的功能,咱们使用Python来代替动态连接库形式的插件,这样能够方便地根据需求的变化 改写脚本代码,而不是必须从新编译连接二进制的动态连接库。Python强大的功能足以胜任,可是有一些操做系统特定的功能须要用C++来实现,再由 Python调用。因此,最基础地,咱们须要作到:网络
1. 把Python嵌入到C++应用程序中,在C++程序中调用Python函数和得到变量的值;数据结构
2. 用C++为Python编写扩展模块(动态连接库),在Python程序中调用C++开发的扩展功能函数。app
下面是例子中用到的几个Python/C API的简要介绍及示例代码。注意,这并非这些函数的详细介绍,而仅仅是咱们所用到的功能简介,更详细内容请参考文档[1]、[2]、[3]、[4]。编程语言
打开Microsoft Visual Studio .NET 2003,新建一个控制台程序,#include ,并在main函数里加入示例代码。函数
//先定义一些变量 char *cstr;2.PyObject *pstr, *pmod, *pdict; PyObject *pfunc, *pargs;
初始化Python解释器,在C++程序中使用其它Python/C API以前,必须调用此函数,若是调用失败,将产生一个致命的错误。例:
Py_Initialize();
执行一段Python代码,就好象是在__main__ 函数里面执行同样。例:
PyRun_SimpleString("from time import time,ctime\n" "print ''Today is'',ctime(time())\n");
导入一个Python模块,参数name能够是*.py文件的文件名。至关于Python内建函数__import__()。例:
pmod = PyImport_ImportModule("mymod"); //mymod.py
至关于Python模块对象的__dict__ 属性,获得模块名称空间下的字典对象。例:
pdict = PyModule_GetDict(pmod);
执行一段Python代码。
pstr = PyRun_String("message", Py_eval_input, pdict, pdict);
解构Python数据为C的类型,这样C程序中才可使用Python里的数据。例:
/* convert to C and print it*/ PyArg_Parse(pstr, "s", &cstr); printf("%s\n", cstr);
返回模块对象o中的attr_name 属性或函数,至关于Python中表达式语句:o.attr_name。例:
/* to call mymod.transform(mymod.message) */ pfunc = PyObject_GetAttrString(pmod, "transform");
构建一个参数列表,把C类型转换为Python对象,使Python可使用C类型数据,例:
cstr="this is hjs''s test, to uppercase"; pargs = Py_BuildValue("(s)", cstr);
此函数有两个参数,都指向Python对象指针,pfunc是要调用的Python 函数,一般可用PyObject_GetAttrString()得到;pargs是函数的参数列表,一般可用Py_BuildValue()构建。例:
pstr = PyEval_CallObject(pfunc, pargs); PyArg_Parse(pstr, "s", &cstr); printf("%s\n", cstr);
关闭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代码中调用这个动态连接库:
1.import pyUtil 2.result = pyUtil.Recognise("input url of specific data") 3.print "the result is: "+ result
用C++为Python写扩展时,若是您愿意使用Boost.Python库的话,开发过程会变得更开心,要编写一个与上述pyUtil一样功能的动态 连接库,只需把文件内容替换为下面的代码。固然,编译须要boost_python.lib支持,运行须要boost_python.dll支持。
01.#include< string > 02.#include < boost/python.hpp > 03.using namespace boost::python; 04.#pragma comment(lib, "boost_python.lib") 05.std::string strtmp; 06.char const* Recognise(const char* url) 07.{ 08.strtmp ="从dll中返回的数据... : "; 09.strtmp+=url; 10.return strtmp.c_str(); 11.} 12.BOOST_PYTHON_MODULE(pyUtil) 13.{ 14.def("Recognise", Recognise); 15.}
全部示例都在Microsoft Windows XP Professional + Microsoft Visual Studio .NET 2003 + Python2.4环境下测试经过,本文所用的Boost库为1.33版本。
附1 text.txt this is test text in text.txt.
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 using std::string; #include //-------------------------------------------------------------------- // Purpose: ease the job to embed Python into C++ applications // by hujinshan @2005年9月2日9:13:18 //-------------------------------------------------------------------- class CSimplepy // : private noncopyable { public: ///constructor CSimplepy() { Py_Initialize(); pstr=NULL, pmod=NULL, pdict=NULL; pfunc=NULL, pargs=NULL; } ///destructor virtual ~CSimplepy() { Py_Finalize(); } ///import the user module bool ImportModule(const char* mod_name) { try{ pmod = PyImport_ImportModule(const_cast(mod_name)); if(pmod==NULL) return false; pdict = PyModule_GetDict(pmod); } catch(...) { return false; } if(pmod!=NULL && pdict!=NULL) return true; else return false; } ///Executes the Python source code from command in the __main__ module. ///If __main__ does not already exist, it is created. ///Returns 0 on success or -1 if an exception was raised. ///If there was an error, there is no way to get the exception information. int Run_SimpleString(const char* str) { return PyRun_SimpleString(const_cast(str) ); } ///PyRun_String("message", Py_eval_input, pdict, pdict); ///Execute Python source code from str in the context specified by the dictionaries globals. ///The parameter start specifies the start token that should be used to parse the source code. ///Returns the result of executing the code as a Python object, or NULL if an exception was raised. string Run_String(const char* str) { char *cstr; pstr = PyRun_String(str, Py_eval_input, pdict, pdict); if(pstr==NULL) throw ("when Run_String, there is an exception was raised by Python environment."); PyArg_Parse(pstr, "s", &cstr); return string(cstr); } ///support olny one parameter for python function, I think it''s just enough. string CallObject(const char* func_name, const char* parameter) { pfunc=NULL; pfunc = PyObject_GetAttrString(pmod, const_cast(func_name)); if(pfunc==NULL) throw (string("do not found in Python module for: ") +func_name).c_str(); char* cstr; pargs = Py_BuildValue("(s)", const_cast(parameter)); pstr = PyEval_CallObject(pfunc, pargs); if(pstr==NULL) throw ("when PyEval_CallObject, there is an exception was raised by Python environment"); PyArg_Parse(pstr, "s", &cstr); return string(cstr); } //PyObject *args; //args = Py_BuildValue("(si)", label, count); /* make arg-list */ //pres = PyEval_CallObject(Handler, args); protected: PyObject *pstr, *pmod, *pdict; PyObject *pfunc, *pargs; }; #endif // _SIMPLEPY_H_ // end of file
[1] Python Documentation Release 2.4.1. 2005.3.30,若是您以默认方式安装了Python2.4,那么该文档的位置在C:\Program Files\Python24\Doc\Python24.chm;
[2] Michael Dawson. Python Programming for the Absolute Beginner. Premier Press. 2003;
[3] Mark Lutz. Programming Python, 2nd Edition. O''Reilly. 2001.3 ;
[4] Mark Hammond, Andy Robinson. Python Programming on Win32. O''Reilly. 2000.1 ;
Python主页:http://www.python.org;
Boost库主面:www.boost.org;