(Python編程)整合代碼產生器SWIG

來源:互聯網
上載者:User
Programming Python, 3rd Edition 翻譯
最新版本見: http://wiki.woodpecker.org.cn/moin/PP3eD

22.6. The SWIG Integration Code Generator

22.6. 整合代碼產生器SWIG

But don't do that. As you can probably tell, manual coding of C extensions can become fairly involved (this is almost inevitable in C language work). I've introduced the basics in this chapter thus far so that you understand the underlying structure. But today, C extensions are usually better and more easily implemented with a tool that generates all the required integration glue code automatically. There are a variety of such tools for use in the Python world, including SIP, SWIG, and Boost.Python; we'll explore alternatives at the end of this chapter. Of these, the SWIG system is likely still the most widely used.

但是,我們不必手工編碼。正如你所知,手工編寫C擴充是相當複雜的(C語言的活兒就是這樣)。目前為止,本章介紹的內容只是基礎知識,用來協助你理解底層的構造。如今,C擴充通常使用工具來自動產生所有的整合粘合代碼,比手工實現更好更輕鬆。這樣的工具有許多,如SIP, SWIG, 及Boost.Python;我們會在本章末尾探索各種不同的工具。而其中,SWIG可能是使用最廣泛的工具。

The Simplified Wrapper and Interface Generator (SWIG) is an open source system created by Dave Beazley and now developed by its community, much like Python. It uses C and C++ type declarations to generate complete C extension modules that integrate existing libraries for use in Python scripts. The generated C (and C++) extension modules are complete: they automatically handle data conversion, error protocols, reference-count management, and more.

SWIG (簡單封裝和介面產生器)是一個開放原始碼系統,由Dave Beazley建立,現由其社群開發,很像Python. 它利用C和C++型別宣告來產生完整的C擴充模組,產生的C擴充模組可以整合到現有庫中供Python指令碼使用。產生的C(和C++)擴充模組是完整的:它們自動處理資料轉換,錯誤處理,引用計數,等等。

That is, SWIG is a program that automatically generates all the glue code needed to plug C and C++ components into Python programs; simply run SWIG, compile its output, and your extension work is done. You still have to manage compilation and linking details, but the rest of the C extension task is largely performed by SWIG.

就是說,SWIG是一個程式,它能自動產生所有粘合代碼,將C和C++組件插入到Python程式中;只需運行SWIG,編譯其輸出代碼,你的擴充模組就完成了。你仍須編譯和連結,但是C擴充的其它大部份工作都可由SWIG完成。

22.6.1. A Simple SWIG Example

22.6.1. 一個SWIG簡例

To use SIWG, instead of writing all that C code in the prior sections, write the C function you want to use from Python without any Python integration logic at all, as though it is to be used from C alone. For instance, Example 22-5 is a recoding of Example 22-1 as a straight C function.

使用SWIG,你不必有任何Python整合的邏輯,不必編寫前面幾節那樣的代碼,只需編寫你的C函數,就像它是僅用於C語言的。例如,例22-5是對例22-1的重寫,是一個純粹的C函數。

Example 22-5. PP3E/Integrate/Extend/HelloLib/hellolib.c
/**/ /*********************************************************************
 * A simple C library file, with a single function, "message",
 * which is to be made available for use in Python programs.
 * There is nothing about Python here--this C function can be
 * called from a C program, as well as Python (with glue code).
 *
 * 一個簡單的C語言庫檔案,只有一個函數,"message",
 * 將會成為可被Python程式使用的函數。
 * 這裡沒有任何Python相關的東西——這個C函數可以
 * 由C程式調用,也可以由Python程式調用(加上粘合代碼後)。
 *********************************************************************/

#include  < string .h >
#include  < hellolib.h >

static   char  result[ 64 ];                   /**/ /* this isn't exported */

char   *
message( char   * label)                      /**/ /* this is exported */
... {
    strcpy(result, "Hello, ");           /**//* build up C string */
    strcat(result, label);               /**//* add passed-in label */
    return result;                       /**//* return a temporary */
}

While you're at it, define the usual C header file to declare the function externally, as shown in Example 22-6. This is probably overkill for such a small example, but it will prove a point.

然後,寫個普通的標頭檔來聲明外部函數,如例22-6所示。對於這樣一個小例子來說,這好像是多餘的,但是下面將會用到。

Example 22-6. PP3E/Integrate/Extend/HelloLib/hellolib.h
/**/ /********************************************************************
 * Define hellolib.c exports to the C namespace, not to Python
 * programs--the latter is defined by a method registration
 * table in a Python extension module's code, not by this .h;
 *
 * 定義hellolib.c輸出到C語言的符號(不是輸出到Python程式)。
 * 輸出到Python程式的符號在Python擴充模組代碼中由一個方法註冊表定義,
 * 而不是在這個.h檔案中。
 ********************************************************************/

extern   char   * message( char   * label);

Now, instead of all the Python extension glue code shown in the prior sections, simply write a SWIG type declarations input file, as in Example 22-7.

現在,無需前幾節所示的所有Python擴充粘合代碼,只需簡單地寫一個SWIG型別宣告輸入檔案,如例22-7。

Example 22-7. PP3E/Integrate/Extend/Swig/hellolib.i
/**/ /******************************************************
 * Swig module description file, for a C lib file.
 * Generate by saying "swig -python hellolib.i".
 ******************************************************/

% module hellowrap

% ... {
#include <hellolib.h>
%}

extern   char   * message( char * );     /**/ /* or: %include "../HelloLib/hellolib.h"   */
                                                          /**/ /* or: %include hellolib.h, and use -I arg */


This file spells out the C function's type signature. In general, SWIG scans files containing ANSI C and C++ declarations. Its input file can take the form of an interface description file (usually with a .i suffix) or a C/C++ header or source file. Interface files like this one are the most common input form; they can contain comments in C or C++ format, type declarations just like standard header files, and SWIG directives that all start with %. For example:

這個檔案列出了C函數的類型簽名。通常,SWIG需要掃描包含ANSI C和C++聲明的檔案,它的輸入檔案可以是一個介面描述檔案(通常是.i尾碼),也可以是一個C/C++標頭檔或源檔案。介面檔案是最常用的形式,就像這個,可以包含C或C++格式的注釋,與標準標頭檔一樣的型別宣告,以及以%開頭的SWIG指令。例如:

%module

Sets the module's name as known to Python importers.

%module 設定模組名,Python匯入的就是這個名字。

%{...%}

Encloses code added to generated wrapper file verbatim.

%{...%}括起來的代碼將原封不動地添加到產生的封裝檔案中。

extern statements

Declare exports in normal ANSI C/C++ syntax.

extern語句用標準的ANSI C/C++文法聲明輸出的符號。

%include

Makes SWIG scan another file (-I flags give search paths).

%include命令SWIG掃描另一個檔案(可以用-I標誌給出搜尋路徑)。

In this example, SWIG could also be made to read the hellolib.h header file of Example 22-6 directly. But one of the advantages of writing special SWIG input files like hellolib.i is that you can pick and choose which functions are wrapped and exported to Python, and you may use directives to gain more control over the generation process.

在本例中,SWIG也可以直接讀取例22-6的hellolib.h標頭檔。但是,專門寫一個像hellolib.i這樣的SWIG輸入檔案至少有一個好處,就是你可以挑選哪些函數要封裝並輸出到Python,而且你還可以用指令來更好地控制碼的產生。

SWIG is a utility program that you run from your build scripts; it is not a programming language, so there is not much more to show here. Simply add a step to your makefile that runs SWIG and compile its output to be linked with Python. Example 22-8 shows one way to do it on Cygwin.

SWIG是由構建指令碼調用的通用程式,它不是一種程式設計語言,所以也沒什麼好講的。只需在make檔案中添加一步運行SWIG,然後就可以編譯SWIG的輸出,並與Python連結。例22-8展示了在Cygwin上的做法。

Example 22-8. PP3E/Integrate/Extend/Swig/makefile.hellolib-swig
##################################################################
# Use SWIG to integrate hellolib.c 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.