SWIG 封裝C++接口給Python調用

什麼是SWIG

SWIG is a software development tool that connects programs written in
C and C++ with a variety of high-level programming languages. SWIG is
used with different types of target languages including common
scripting languages such as Javascript, Perl, PHP, Python, Tcl and
Ruby. The list of supported languages also includes non-scripting
languages such as C#, D, Go language, Java including Android, Lua,
OCaml, Octave, Scilab and R. Also several interpreted and compiled
Scheme implementations (Guile, MzScheme/Racket) are supported. SWIG is
most commonly used to create high-level interpreted or compiled
programming environments, user interfaces, and as a tool for testing
and prototyping C/C++ software. SWIG is typically used to parse C/C++
interfaces and generate the ‘glue code’ required for the above target
languages to call into the C/C++ code. SWIG can also export its parse
tree in the form of XML. SWIG is free software and the code that SWIG
generates is compatible with both commercial and non-commercial
projects.

簡單來說SWIG就是 各種編程語言的 轉換器,可以將C++代碼編譯給Python調用。

下載

SWIG官網下載:https://sourceforge.net/projects/swig/files/swigwin

外網下載較慢,我這裏有較新的一個windows版本 swigwin-4.0.1.zip

鏈接:https://pan.baidu.com/s/1tIe8S2Yr_R3qSzFI9hb9Xw 提取碼:zeei

添加系統環境變量

下載完之後解壓縮到一個地方,copy文件夾地址,比如我的是 D:\App\swigwin-4.0.1
控制面板>編輯系統環境變量,可以直接點擊鍵盤 Win 鍵搜索 關鍵字 “環境變量
在這裏插入圖片描述
用戶變量 > Path > 新增 D:\App\swigwin-4.0.1

使用C++封裝

編寫封裝說明文件

swig封裝需要一個.i後綴文件的封裝說明,其中

  • %module name 爲封裝名稱,Python調用的包名就是 name
  • %{…%} 爲附加的函數說明和頭文件,源文件以外的部分都要包括在這裏,包括頭文件和宏定義等
    之後爲要封裝的函數或類,可以直接引用頭文件(若已經將要封裝的部分的聲明寫在頭文件中)
%module Example_swig
%{
#include "example.h"
%}

%include "example.h"

調用swig封裝

在命令行中輸入swig -python -c++ <swig_config>.i,其中<swig_config>.i爲上面寫的說明文件

swig -python -c++ example.i

調用後生成兩個文件:

  • name_wrap.cxx文件
  • name.py文件
  • 我們把這裏的c/c++文件叫做low-level,生成的py叫做high-level,對於c/c++的生成文件需要進行編譯並鏈接其餘的部分(文件中所引用的東西)創建一個擴展module,對於py文件,就是要導入的文件。
  • 說下名字的問題。比如我們用的module:test.i就會默認生成一個加了_wrap的包裝器test_wrap.c。如果要更改的話,可以使用swig的可選項-o指定。生成的py文件就是同名的.py文件。

使用VS編譯

1. 新建動態鏈接庫項目

文件 > 新建 > 項目
在這裏插入圖片描述

2. 配置輸出類型

生成 > 配置管理器 中設置:

  • 活動解決方案配置爲Release
  • 活動解決方案平臺爲X64(本機爲64位機)

在這裏插入圖片描述

3. 添加Python 庫
  • 項目>屬性 中配置Python的庫

  • 在VC++目錄中的 包含目錄 中,導入Python安裝路徑下的include路徑(包含Python.h)
    比如我的是 C:\Apps\anaconda3.6\include

  • 鏈接器 > 常規 的附加庫目錄中,導入Python安裝路徑下的libs路徑(注意不是Lib路徑,包括dll文件)
    比如我的是 C:\Apps\anaconda3.6\libs

  • 將之前生成的 name_wrap.cxx 添加到工程源文件中
    源文件 > 添加 > 現有項
    在這裏插入圖片描述

  • 最後點擊確定
    在這裏插入圖片描述

編譯輸出

  • 選擇 生成 > 生成解決方案,在X64->Release文件夾下有一個dll文件,即爲編譯輸出的動態鏈接庫。
  • 將其名稱改爲**_name.pyd**(本例中爲**_ZQGL2.pyd**),將其與swig生成的name.py文件放在同一目錄中

調用測試

import ...

參考

Windows平臺下Python使用swig調用C++
swig 實踐(python & c/c++)(一)

發佈了66 篇原創文章 · 獲贊 81 · 訪問量 58萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章