1. 程式人生 > >VC和Python的互相呼叫

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 <Python.h>,並在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,ctime\n"
"print ''Today is'',ctime(time())\n");
3. PyObject* PyImport_ImportModule( char *name)

匯入一個Python模組,引數name可以是*.py檔案的檔名。相當於Python內建函式__import__()。例:

pmod = PyImport_ImportModule("mymod"); //mymod.py
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("%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] 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