使用SWIG包裝C/C++供Python使用


有多種方法可以將現有的C或C++功能包裝到Python中。在本節中,我們將瞭解如何使用SWIG包裝C/C++功能。以下是其他在python中包裝c/c++功能的選項。

  • 手動包裝
  • 使用pyrex包裝C程式碼。
  • Ctypes
  • SIP
  • Boost Python

SWIG(簡單的包裝器介面生成器)能夠使用多種其他語言包裝C程式碼,包括Perl、Python、PHP、Ruby、Tcl、C#、Common Lisp(CLISP、Allegro、CL、UFFI、CFFI)、Java、Modula-3和OCAML。Swig還支援多種解釋型和編譯型Scheme實現(如Guile、MzScheme、Chicken)。

但這裡我們只討論它與python的實現。

SWIG本質上是一種宏語言,它理解C程式碼,然後會為選擇的語言輸出包裝程式碼。

安裝

我使用的是“swigwin-3.0.12” windows swig安裝程式,您可以從以下地址下載:

http://www.swig.org/download.html

除此之外,您可能需要“Microsoft Visual Studio 14.0”或更高版本才能在Windows上執行swig程式。

為了說明swig的使用,假設我們有一些c函式,我們想將其新增到其他語言中,例如Tcl、Perl、Python(我正在與python互動)、Java和C#。

我的c檔案是example.c

#include "example.h"
int fact(int n) {
   if (n < 0) {       /* This should probably return an error, but this is simpler */
      return 0;
   }
   if (n == 0) {
      return 1;
   } else {
      /* testing for overflow would be a good idea here */
      return n * fact(n-1);
   }
}

介面檔案

現在,如果您想將您的c檔案新增到您喜歡的語言中,您需要編寫一個“介面檔案”,它是SWIG的輸入。我的example.c的介面檔案是:

example.i

/* File: example.i */
%module example
%{
   #define SWIG_FILE_WITH_INIT
   #include "example.h"
%}
%include "example.h"

標頭檔案

我們在之前的示例檔案中包含了標頭檔案。所以這是我的標頭檔案

example.h

int fact(int n);

設定檔案

from distutils.core import setup, Extension
example_module = Extension('_example',
   sources=['example_wrap.c', 'example.c'],
)
setup (name = 'example',
   version = '0.1',
   author = "SWIG Docs",
   description = """Simple swig example from docs""",
   ext_modules = [example_module],
   py_modules = ["example"],
)

建立包裝器

現在我們將使用我們的介面檔案(example.i)建立python包裝器。要為您的函式建立包裝器,只需在您的CLI上執行以下命令。

>swig -python example.i

現在如果您檢視您的當前工作目錄,就會發現剛剛建立了一個新檔案。如果您使用的是與我相同的檔名,那麼您的包裝器檔案將是“example_wrap.c”,否則包裝器檔案將被命名為類似

“Your_File_Name” + “_wrapper” + “Your_language_extension”

因此,如果您的示例檔案是test.c,那麼您的包裝器檔案將是“test_wrapper.c”。

構建擴充套件

>python setup.py build_ext
running build_ext
building '_example' extension
creating build
creating build\temp.win32-3.6
creating build\temp.win32-3.6\Release
….

就是這樣,現在我們能夠將我們的c語言包裝到python語言中。要檢查它,您可以直接執行或建立一個虛擬環境並單獨執行。

C:\Users\rajesh>mkdir swigExample && cd swigExample
C:\Users\rajesh\swigExample>virtualenv swigenv
Using base prefix 'c:\python\python361'
New python executable in C:\Users\rajesh\swigExample\swigenv\Scripts\python.exe
Installing setuptools, pip, wheel...done.

C:\Users\rajesh\swigExample>.\swigenv\Scripts\activate

(swigenv) C:\Users\rajesh\swigExample>python

就是這樣,現在從您的檔案中匯入函式並執行它。

>>> from example import fact
>>> fact(6)
720

更新於:2019年7月30日

1K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.