VC和Python的互相调用

VC和Python的互相调用

2023年7月10日发(作者:)

VC和Python的互相调⽤在某个C++应⽤程序中,我们⽤⼀组插件来实现⼀些具有统⼀接⼝的功能,我们使⽤Python来代替动态链接库形式的插件,这样可以⽅便地根据需求的变化改写脚本代码,⽽不是必须重新编译链接⼆进制的动态链接库。Python强⼤的功能⾜以胜任,但是有⼀些操作系统特定的功能需要⽤C++来实现,再由Python调⽤。所以,最基础地,我们需要做到:1. 把Python嵌⼊到C++应⽤程序中,在C++程序中调⽤Python函数和获得变量的值;2. ⽤C++为Python编写扩展模块(动态链接库),在Python程序中调⽤C++开发的扩展功能函数。常⽤的Python/C API介绍  下⾯是例⼦中⽤到的⼏个Python/C API的简要介绍及⽰例代码。注意,这并不是这些函数的详细介绍,⽽仅仅是我们所⽤到的功能简介,更详细内容请参考⽂档[1]、[2]、[3]、[4]。打开Microsoft Visual Studio .NET 2003,新建⼀个控制台程序,#include ,并在main函数⾥加⼊⽰例代码。//先定义⼀些变量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,ctimen""print ''Today is'',ctime(time())n");3. PyObject* PyImport_ImportModule( char *name)

导⼊⼀个Python模块,参数name可以是*.py⽂件的⽂件名。相当于Python内建函数__import__()。例:pmod = PyImport_ImportModule("mymod"); //4. 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("%sn", cstr);7. PyObject* PyObject_GetAttrString( PyObject *o, char *attr_name)

返回模块对象o中的attr_name 属性或函数,相当于Python中表达式语句:_name。例:/* to call orm(e) */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("%sn", cstr);10. void Py_Finalize( )

关闭Python解释器,释放解释器所占⽤的资源。例:Py_Finalize();  Python2.4环境没有提供调试版本的,所以上述⽰例在release模式下编译。编译完成后,把可⾏⽂件和附2给出的⽂件放在⼀起,再点击即可运⾏。为了简化编程,附3 给出了simplepy.h。这样,调⽤orm变成如下形式://#include”simplepy.h”CSimplepy py;Module("mymod");std::string str=ject("transform",

"this is hjs''s test, to uppercase");printf("%sn", str.c_str());  接下来,我们来⽤C++为Python编写扩展模块(动态链接库),并在Python程序中调⽤C++开发的扩展功能函数。⽣成⼀个取名为pyUtil的Win32 DLL⼯程,除了⽂件以外,从⼯程中移除所有其它⽂件,并填⼊如下的代码:// #ifdef PYUTIL_EXPORTS#define PYUTIL_API __declspec(dllexport)#else#define PYUTIL_API __declspec(dllimport)#endif#include#include#includeBOOL 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 pyUtilresult = ise("input url of specific data")print "the result is: "+ result

  ⽤C++为Python写扩展时,如果您愿意使⽤库的话,开发过程会变得更开⼼J,要编写⼀个与上述pyUtil同样功能的动态链接库,只需把⽂件内容替换为下⾯的代码。当然,编译需要boost_⽀持,运⾏需要boost_⽀持。#include#include using namespace boost::python;#pragma comment(lib, "boost_")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] Python Documentation Release 2.4.1. 2005.3.30,如果您以默认⽅式安装了Python2.4,那么该⽂档的位置在C:;[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主页:;Boost库主⾯:;附1 s is test text in .附2 rt stringmessage = ''original string''message =message+messagemsg_error=""try: text_file = open("", "r") whole_thing = text_() print whole_thing text_()except IOError, (errno, strerror): print "I/O error(%s): %s" % (errno, strerror)def transform(input): #input = e(input, ''life'', ''Python'') return (input)

def change_msg(nul):

global message #如果没有此⾏,message是函数⾥头的局部变量 message=''string changed'' return messagedef r_file(nul): return whole_thingdef 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)); 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

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688930986a184745.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信