• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            任我行

            一天一個腳印......
            每日一句:
            posts - 54, comments - 218, trackbacks - 1, articles - 0
              C++博客 :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

            C++ 擴展和嵌入 Python

            Posted on 2005-11-02 14:57 任我行 閱讀(1810) 評論(2)  編輯 收藏 引用 所屬分類: Python

            下載源代碼

            Python簡介

              Python是一種簡單易學(xué),功能強大的解釋型編程語言,它有簡潔明了的語法,高效率的高層數(shù)據(jù)結(jié)構(gòu),能夠簡單而有效地實現(xiàn)面向?qū)ο缶幊蹋貏e適用于快速應(yīng)用程序開發(fā),也可以用來開發(fā)大規(guī)模的重要的商業(yè)應(yīng)用。Python是一個理想的腳本語言。
              Python免費開源,可移植到多種操作系統(tǒng),只要避免使用依賴于特定操作系統(tǒng)的特性,Python程序無需修改就可以在各種平臺上面運行。
              Python擁有現(xiàn)代編程語言所具有的一切強大功能,Python標(biāo)準(zhǔn)庫十分龐大,可以幫助開發(fā)者處理各種工作,如:圖形用戶界面、文件處理、多媒體、正則表達式、文檔生成、單元測試、線程、數(shù)據(jù)庫、網(wǎng)絡(luò)通訊、網(wǎng)頁瀏覽器、CGI、FTP、電子郵件、XML、HTML、WAV文件、密碼系統(tǒng)、Tk和其他與系統(tǒng)有關(guān)的操作。只要安裝了Python,這些功能都是可用的除了標(biāo)準(zhǔn)庫以外,還有許多其他高質(zhì)量的庫,如wxPython、Twisted和Python圖形庫等等數(shù)不勝數(shù)。
              Python容易擴展和嵌入。Python提供的許多標(biāo)準(zhǔn)模塊支持C或者C++接口。Python和C可以一起工作,它可以嵌入到C或者C++的應(yīng)用程序當(dāng)中,因此可用Python語言為應(yīng)用程序提供腳本接口,由于支持跨語言開發(fā),可用Python設(shè)計概念化應(yīng)用程序,并逐步移植到C,使用前不必用C重寫應(yīng)用程序。(Jython使Python可以和Java一起工作,使開發(fā)者可以在Python里面調(diào)Java的包,也可以在Java里面使用Python的對象。還有更妙的,由于Jython的解釋器完全用Java編寫,因此可以在支持Java的任何平臺上部署Python程序,甚至WEB瀏覽器也可以直接運行Python腳本。)

            提出問題

              在某個C++應(yīng)用程序中,我們用一組插件來實現(xiàn)一些具有統(tǒng)一接口的功能,我們使用Python來代替動態(tài)鏈接庫形式的插件,這樣可以方便地根據(jù)需求的變化改寫腳本代碼,而不是必須重新編譯鏈接二進制的動態(tài)鏈接庫。Python強大的功能足以勝任,但是有一些操作系統(tǒng)特定的功能需要用C++來實現(xiàn),再由Python調(diào)用。所以,最基礎(chǔ)地,我們需要做到:

            • 1. 把Python嵌入到C++應(yīng)用程序中,在C++程序中調(diào)用Python函數(shù)和獲得變量的值;
            • 2. 用C++為Python編寫擴展模塊(動態(tài)鏈接庫),在Python程序中調(diào)用C++開發(fā)的擴展功能函數(shù)。

            常用的Python/C API介紹

              下面是例子中用到的幾個Python/C API的簡要介紹及示例代碼。注意,這并不是這些函數(shù)的詳細(xì)介紹,而僅僅是我們所用到的功能簡介,更詳細(xì)內(nèi)容請參考文檔[1]、[2]、[3]、[4]。
            打開Microsoft Visual Studio .NET 2003,新建一個控制臺程序,#include <Python.h>,并在main函數(shù)里加入示例代碼。
            //先定義一些變量

            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)生一個致命的錯誤。例:
            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)入一個Python模塊,參數(shù)name可以是*.py文件的文件名。相當(dāng)于Python內(nèi)建函數(shù)__import__()。例:

            pmod = PyImport_ImportModule("mymod"); //mymod.py
            
            4. PyObject* PyModule_GetDict( PyObject *module)

            相當(dāng)于Python模塊對象的__dict__ 屬性,得到模塊名稱空間下的字典對象。例:

            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)

            返回模塊對象o中的attr_name 屬性或函數(shù),相當(dāng)于Python中表達式語句:o.attr_name。例:

            /* to call mymod.transform(mymod.message) */
            pfunc = PyObject_GetAttrString(pmod, "transform");
            
            8. PyObject* Py_BuildValue( char *format, ...)

            構(gòu)建一個參數(shù)列表,把C類型轉(zhuǎn)換為Python對象,使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ù)有兩個參數(shù),都指向Python對象指針,pfunc是要調(diào)用的Python 函數(shù),通常可用PyObject_GetAttrString()獲得;pargs是函數(shù)的參數(shù)列表,通常可用Py_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)境沒有提供調(diào)試版本的Python24d.lib,所以上述示例在release模式下編譯。編譯完成后,把可行文件和附2給出的mymod.py文件放在一起,再點擊即可運行。為了簡化編程,附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());

              接下來,我們來用C++為Python編寫擴展模塊(動態(tài)鏈接庫),并在Python程序中調(diào)用C++開發(fā)的擴展功能函數(shù)。生成一個取名為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)用這個動態(tài)鏈接庫:
            import pyUtil
            result = pyUtil.Recognise("input url of specific data")
            print "the result is: "+ result		
              用C++為Python寫擴展時,如果您愿意使用Boost.Python庫的話,開發(fā)過程會變得更開心J,要編寫一個與上述pyUtil同樣功能的動態(tài)鏈接庫,只需把文件內(nèi)容替換為下面的代碼。當(dāng)然,編譯需要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中返回的數(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)境下測試通過,本文所用的Boost庫為1.33版本。

            參考資料
            • [1] Python Documentation Release 2.4.1. 2005.3.30,如果您以默認(rèn)方式安裝了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是函數(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 
            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 
            ---作者:胡金山

            Feedback

            # re: C++ 擴展和嵌入 Python  回復(fù)  更多評論   

            2006-05-16 18:29 by guest
            編譯的時候會報告如下錯誤:'void' should be preceded by ';'
            指向的是下面的代碼:
            extern "C" PYUTIL_API void initpyUtil() //這一行出錯
            {
            PyObject *m, *d;
            m = Py_InitModule("pyUtil", AllMyMethods); //初始化本模塊,并暴露函數(shù)
            d = PyModule_GetDict(m);
            }

            希望得到指教

            # re: C++ 擴展和嵌入 Python  回復(fù)  更多評論   

            2006-06-10 13:12 by 空明流轉(zhuǎn)
            這樣寫太復(fù)雜了,不如用boost的。
            国产激情久久久久久熟女老人| 国产精品欧美久久久久无广告| 国产精品久久久久久久人人看| 久久久午夜精品| 无码人妻久久一区二区三区| 97久久超碰国产精品2021| 国产精品99久久久久久www| 久久精品国产男包| 久久国产精品一区二区| yy6080久久| 国产精品丝袜久久久久久不卡| 伊人久久一区二区三区无码| 久久亚洲日韩精品一区二区三区| 久久精品一区二区三区不卡| 久久亚洲精品国产精品婷婷| 久久精品国产亚洲网站| 久久AV无码精品人妻糸列| 久久国产精品免费一区| 久久婷婷成人综合色综合| 人妻无码精品久久亚瑟影视| 99热成人精品热久久669| 97精品伊人久久大香线蕉| AAA级久久久精品无码区| www久久久天天com| 亚洲精品白浆高清久久久久久| 久久国产视屏| 精品欧美一区二区三区久久久| 国内精品久久久久久久97牛牛| 亚洲国产成人精品91久久久 | 欧美黑人又粗又大久久久| 久久免费精品视频| 狠狠久久亚洲欧美专区| 久久九九精品99国产精品| 久久夜色精品国产噜噜噜亚洲AV| 天天做夜夜做久久做狠狠| 久久精品亚洲乱码伦伦中文| 99久久精品免费看国产免费| 久久这里只精品国产99热| 一本色道久久88加勒比—综合| 国产精品久久久久久久久免费| 久久精品国产99久久无毒不卡|