安裝
依賴 PCRE 庫
apt-get install libpcre2-dev
下載安裝
$ ./configure
$ make
$ make install
介紹
SWIG 是一個軟件開發工具,能夠簡化不同編程語言與 C 和 C++ 程序連接的開發任務。
簡而言之,SWIG 是一款編譯器,它可以獲取 C/C++ 聲明並創建訪問這些聲明所需的包裝器,從而可從包括 Perl、Python、Tcl、Ruby、Guile 和 Java 在內的其他語言訪問這些聲明。SWIG 通常不需要修改現有代碼,而且通常只需幾分鐘即可構建一個可用的接口。
本質上,SWIG 是一個爲生成代碼而設計的工具,該工具可以讓各種其他編程語言調用 C/C++ 代碼。這些更高級的編程語言是 SWIG 代碼生成器的目標語言,而 C 或 C++ 是輸入語言。在運行 SWIG 時必須指定一種目標語言。這將爲 C/C++ 和指定的目標語言生成代碼,以便相互進行接口
這種將 C/C++ 與許多不同目標語言連接的能力是 SWIG 的核心優勢和特性之一。
從一個c庫開始
假設,這裏有一個c代碼,我們要提供給python和golang、java等調用。
下面是代碼:
/* File : example.c */
double My_variable = 3.0;
/* Compute factorial of n */
int fact(int n) {
if (n <= 1)
return 1;
else
return n*fact(n-1);
}
/* Compute n mod m */
int my_mod(int n, int m) {
return(n % m);
}
你或許會想,是不是要先學習下python擴展如何寫,JNI如何搞,cgo如何弄。。
但是,當你有了SWIG,這一切就變得更簡單了。開始之前,我們首先需要編寫一個swig接口.
swig接口
swig接口,你可以理解爲就像pb文件一樣,要先定義一套標準的接口(interface),然後swig負責根據這個swig interface,去生成連接其他語言的膠水代碼。
%module example
%{
/* Put headers and other declarations here */
extern double My_variable;
extern int fact(int);
extern int my_mod(int n, int m);
%}
extern double My_variable;
extern int fact(int);
extern int my_mod(int n, int m);
- 接口文件包含 C 函數原型和變量聲明。
%module
指令定義了SWIG
將創建的模塊的名稱。{% %}
塊提供了一個位置,用於將其他代碼(如 C 頭文件或附加 C 聲明)插入到生成的 C 包裝器代碼中
接口就緒後,我們可以來生成對應語言的膠水代碼了。
python調用c
首先通過swig -{lang} example.i
生成wrap膠水代碼。
swig -python example.i
這裏會生成;
example_wrap.c
連接c代碼的wrapexample.py
可以類比GRPC生成的訪問wrap的代碼。
我們來看下生成的包裝代碼example_wrap.c
:
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (https://www.swig.org).
* Version 4.1.1
*
* Do not make changes to this file unless you know what you are doing - modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
/* source: example.i */
#define SWIG_VERSION 0x040101
#define SWIGGO
#define SWIGMODULE example
/* -----------------------------------------------------------------------------
* This section contains generic SWIG labels for method/variable
* declarations/attributes, and other compiler dependent labels.
* ----------------------------------------------------------------------------- */
/* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
# define SWIGTEMPLATEDISAMBIGUATOR template
# elif defined(__HP_aCC)
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
# define SWIGTEMPLATEDISAMBIGUATOR template
# else
# define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif
/* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
# else
# define SWIGINLINE
# endif
#endif
/* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
# elif defined(__ICC)
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
#endif
#ifndef SWIG_MSC_UNSUPPRESS_4505
# if defined(_MSC_VER)
# pragma warning(disable : 4505) /* unreferenced local function has been removed */
# endif
#endif
#ifndef SWIGUNUSEDPARM
# ifdef __cplusplus
# define SWIGUNUSEDPARM(p)
# else
# define SWIGUNUSEDPARM(p) p SWIGUNUSED
# endif
#endif
/* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif
/* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif
/* exporting methods */
#if defined(__GNUC__)
# if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
# ifndef GCC_HASCLASSVISIBILITY
# define GCC_HASCLASSVISIBILITY
# endif
# endif
#endif
#ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(STATIC_LINKED)
# define SWIGEXPORT
# else
# define SWIGEXPORT __declspec(dllexport)
# endif
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGEXPORT __attribute__ ((visibility("default")))
# else
# define SWIGEXPORT
# endif
# endif
#endif
/* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# define SWIGSTDCALL __stdcall
# else
# define SWIGSTDCALL
# endif
#endif
/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif
/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif
/* Deal with Apple's deprecated 'AssertMacros.h' from Carbon-framework */
#if defined(__APPLE__) && !defined(__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES)
# define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0
#endif
/* Intel's compiler complains if a variable which was never initialised is
* cast to void, which is a common idiom which we use to indicate that we
* are aware a variable isn't used. So we just silence that warning.
* See: https://github.com/swig/swig/issues/192 for more discussion.
*/
#ifdef __INTEL_COMPILER
# pragma warning disable 592
#endif
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
typedef ptrdiff_t intgo;
typedef size_t uintgo;
# if !defined(__clang__) && (defined(__i386__) || defined(__x86_64__))
# define SWIGSTRUCTPACKED __attribute__((__packed__, __gcc_struct__))
# else
# define SWIGSTRUCTPACKED __attribute__((__packed__))
# endif
typedef struct { char *p; intgo n; } _gostring_;
typedef struct { void* array; intgo len; intgo cap; } _goslice_;
static void Swig_free(void* p) {
free(p);
}
static void* Swig_malloc(int c) {
return malloc(c);
}
/* Put headers and other declarations here */
extern double My_variable;
extern int fact(int);
extern int my_mod(int n, int m);
#ifdef __cplusplus
extern "C" {
#endif
void _wrap_Swig_free_example_c8af3355f0aa50cc(void *_swig_go_0) {
void *arg1 = (void *) 0 ;
arg1 = *(void **)&_swig_go_0;
Swig_free(arg1);
}
void *_wrap_Swig_malloc_example_c8af3355f0aa50cc(intgo _swig_go_0) {
int arg1 ;
void *result = 0 ;
void *_swig_go_result;
arg1 = (int)_swig_go_0;
result = (void *)Swig_malloc(arg1);
*(void **)&_swig_go_result = (void *)result;
return _swig_go_result;
}
void _wrap_My_variable_set_example_c8af3355f0aa50cc(double _swig_go_0) {
double arg1 ;
arg1 = (double)_swig_go_0;
My_variable = arg1;
}
double _wrap_My_variable_get_example_c8af3355f0aa50cc() {
double result;
double _swig_go_result;
result = (double)My_variable;
_swig_go_result = result;
return _swig_go_result;
}
intgo _wrap_fact_example_c8af3355f0aa50cc(intgo _swig_go_0) {
int arg1 ;
int result;
intgo _swig_go_result;
arg1 = (int)_swig_go_0;
result = (int)fact(arg1);
_swig_go_result = result;
return _swig_go_result;
}
intgo _wrap_my_mod_example_c8af3355f0aa50cc(intgo _swig_go_0, intgo _swig_go_1) {
int arg1 ;
int arg2 ;
int result;
intgo _swig_go_result;
arg1 = (int)_swig_go_0;
arg2 = (int)_swig_go_1;
result = (int)my_mod(arg1,arg2);
_swig_go_result = result;
return _swig_go_result;
}
#ifdef __cplusplus
}
#endif
可以看到,自動生成的wrap代碼爲interface裏的函數,變量都生成了包裝函數,通過extern "C"
實現wrap函數導出,後續的其他編程語言可以通過訪問這些導出的wrap函數,實現訪問原來的c函數。
編譯模塊
我們現在來生成一個python代碼模塊。
[root@dev swig_demo]#gcc -c -fpic example.c example_wrap.c -I/root/anaconda3/include/python3.9
[root@dev swig_demo]#gcc -shared example.o example_wrap.o -o _example.so
[root@dev swig_demo]#ll
total 244
drwxr-xr-x 3 root root 4096 Jan 18 19:40 ./
drwxr-xr-x 4 root root 4096 Jan 18 19:28 ../
-rw-r--r-- 1 root root 203 Jan 18 19:28 example.c
-rw-r--r-- 1 root root 244 Jan 18 19:29 example.i
-rw-r--r-- 1 root root 1560 Jan 18 19:39 example.o
-rw-r--r-- 1 root root 2101 Jan 18 19:36 example.py
-rwxr-xr-x 1 root root 52480 Jan 18 19:39 _example.so*
-rw-r--r-- 1 root root 110727 Jan 18 19:36 example_wrap.c
-rw-r--r-- 1 root root 53240 Jan 18 19:39 example_wrap.o
[root@dev swig_demo]#python3
Python 3.9.13 (main, Aug 25 2022, 23:26:10)
[GCC 11.2.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> example.fact(4)
24
>>> example.my_mod(23, 7)
2
>>> example.cvar.My_variable + 4.5
7.5
>>>
swig -python example.i
會生成一個c包裝代碼example_wrap.c
和python 庫代碼example.py
example.py
裏的函數定義和interface一致,實際上裏面有代碼去訪問之前生成的wrap接口。gcc -c -fpic example.c example_wrap.c -I/root/anaconda3/include/python3.9
這裏編譯代碼,需要指定下python include代碼,根據實際位置指定
與CMake等build system集成
swig支持與cmake等集成,我們編寫一個cmakelists.txt文件
FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
FIND_PACKAGE(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(CMAKE_SWIG_FLAGS "")
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall")
SWIG_ADD_MODULE(example python example.i example.c)
SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})
編譯:
[root@dev swig_demo]#mkdir build
[root@dev swig_demo]#cd build/
[root@dev build]#cmake ..
[root@dev build]#make
Scanning dependencies of target example_swig_compilation
[ 25%] Swig compile example.i for python
[ 25%] Built target example_swig_compilation
[ 50%] Building CXX object CMakeFiles/_example.dir/CMakeFiles/_example.dir/examplePYTHON_wrap.o
[ 75%] Building C object CMakeFiles/_example.dir/example.o
[100%] Linking CXX shared module _example.so
[100%] Built target _example
[root@dev build]#ls
CMakeCache.txt CMakeFiles cmake_install.cmake example.py _example.so Makefile
[root@dev build]#ll
total 104
drwxr-xr-x 3 root root 4096 Jan 18 19:51 ./
drwxr-xr-x 4 root root 4096 Jan 18 19:50 ../
-rw-r--r-- 1 root root 15949 Jan 18 19:50 CMakeCache.txt
drwxr-xr-x 7 root root 4096 Jan 18 19:51 CMakeFiles/
-rw-r--r-- 1 root root 1662 Jan 18 19:51 cmake_install.cmake
-rw-r--r-- 1 root root 2101 Jan 18 19:51 example.py
-rwxr-xr-x 1 root root 57472 Jan 18 19:51 _example.so*
-rw-r--r-- 1 root root 6688 Jan 18 19:51 Makefile
golang調用c
Go 並不支持直接調用用 C/C++ 編寫的函數。cgo 程序可用於生成調用 C 代碼的包裝器,但目前沒有直接調用 C++ 代碼的簡單方式。SWIG 填補了這一空白。
默認情況下 SWIG 會生成可以直接被 go build 使用的文件。 Go 需要大於1.2 版本。
同樣上面的example.i, 我們可以
swig -go example.i
go install
上面的命令,會生成example.go
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (https://www.swig.org).
* Version 4.1.1
*
* Do not make changes to this file unless you know what you are doing - modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
// source: example.i
package example
/*
#define intgo swig_intgo
typedef void *swig_voidp;
#include <stddef.h>
#include <stdint.h>
typedef ptrdiff_t intgo;
typedef size_t uintgo;
typedef struct { char *p; intgo n; } _gostring_;
typedef struct { void* array; intgo len; intgo cap; } _goslice_;
extern void _wrap_Swig_free_example_c8af3355f0aa50cc(uintptr_t arg1);
extern uintptr_t _wrap_Swig_malloc_example_c8af3355f0aa50cc(swig_intgo arg1);
extern void _wrap_My_variable_set_example_c8af3355f0aa50cc(double arg1);
extern double _wrap_My_variable_get_example_c8af3355f0aa50cc(void);
extern swig_intgo _wrap_fact_example_c8af3355f0aa50cc(swig_intgo arg1);
extern swig_intgo _wrap_my_mod_example_c8af3355f0aa50cc(swig_intgo arg1, swig_intgo arg2);
#undef intgo
*/
import "C"
import "unsafe"
import _ "runtime/cgo"
import "sync"
type _ unsafe.Pointer
var Swig_escape_always_false bool
var Swig_escape_val interface{}
type _swig_fnptr *byte
type _swig_memberptr *byte
func getSwigcptr(v interface { Swigcptr() uintptr }) uintptr {
if v == nil {
return 0
}
return v.Swigcptr()
}
type _ sync.Mutex
func Swig_free(arg1 uintptr) {
_swig_i_0 := arg1
C._wrap_Swig_free_example_c8af3355f0aa50cc(C.uintptr_t(_swig_i_0))
}
func Swig_malloc(arg1 int) (_swig_ret uintptr) {
var swig_r uintptr
_swig_i_0 := arg1
swig_r = (uintptr)(C._wrap_Swig_malloc_example_c8af3355f0aa50cc(C.swig_intgo(_swig_i_0)))
return swig_r
}
func SetMy_variable(arg1 float64) {
_swig_i_0 := arg1
C._wrap_My_variable_set_example_c8af3355f0aa50cc(C.double(_swig_i_0))
}
func GetMy_variable() (_swig_ret float64) {
var swig_r float64
swig_r = (float64)(C._wrap_My_variable_get_example_c8af3355f0aa50cc())
return swig_r
}
func Fact(arg1 int) (_swig_ret int) {
var swig_r int
_swig_i_0 := arg1
swig_r = (int)(C._wrap_fact_example_c8af3355f0aa50cc(C.swig_intgo(_swig_i_0)))
return swig_r
}
func My_mod(arg1 int, arg2 int) (_swig_ret int) {
var swig_r int
_swig_i_0 := arg1
_swig_i_1 := arg2
swig_r = (int)(C._wrap_my_mod_example_c8af3355f0aa50cc(C.swig_intgo(_swig_i_0), C.swig_intgo(_swig_i_1)))
return swig_r
}
可以看到,生成的代碼默認還是通過cgo去調用swig生成的包裝器wrap代碼。
本質上,SWIG和我們常用的GRPC起到類似的作用:-)
總結
SWIG 建立起java、python等其他高級編程語言調用c/c++ 代碼的橋樑,可以不用瞭解JNI、cgo等複雜的跨語言調用知識,實現一次編寫接口,同步生成多語言接口。