C++ 扩展和嵌入 Python





http://wenku.baidu.com/view/01fa40116edb6f1aff001fce.html























































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:\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;  
附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  
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值