SWIG(Simplified Wrapper and Interface Generator),是一款开源软件,其目的是将C/C++编写的函数库封装成其他语言的接口,包括:Java, Python, Perl, Ruby, C#, PHP等诸多主流编程语言。SWIG底层仍然还是JNI。
Swig可应用于包括windows、mac os x和linux在内的大多数操作系统平台。使用swig需要生成一个.i的接口文件,swig接口文件包含函数原型、类和变量声明,它的语法和普通的c/c++头文件一样。除了c/c++关键字和预处理器指令,接口文件还包含swig特有的预处理器指令,该指令可用于优化生成封装代码。
Swig 网站:https://www.swig.org/
Swig github :https://github.com/swig/swig
在macOS下,使用brew比较方便,能省去一些配置过程(pcre):
brew install swig
查看是否安装成功
swig -version
int counter = 0;
%module example
%{
#include "example.h"
%}
extern int counter;
swig -java example.i
public class test {
static {
System.setProperty("java.library.path", ".");
System.loadLibrary("example");
}
public static void main(String[] args) {
System.out.println(example.getCounter());
example.setCounter(1);
System.out.println(example.getCounter());
}
}
gcc -dynamiclib -I /Users/dry/Library/Java/JavaVirtualMachines/azul-1.8.0_312/Contents/Home/include *.c -o libexample.dylib
javac -d . *.java
java test
gcc -I 后面的路径是 本机 jni 所在路径 (通过jdk所在目录查找)
/* File : example.c */
/* A global variable */
double Foo = 3.0;
/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
int g;
g = y;
while (x > 0) {
g = x;
x = y % x;
y = g;
}
return g;
}
/* File : example.i */
%module example
%inline %{
extern int gcd(int x, int y);
extern double Foo;
%}
swig -java example.i
public class test {
static {
try {
System.loadLibrary("example");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
System.exit(1);
}
}
public static void main(String argv[]) {
// Call our gcd() function
int x = 42;
int y = 105;
int g = example.gcd(x,y);
System.out.println("The gcd of " + x + " and " + y + " is " + g);
// Manipulate the Foo global variable
// Output its current value
System.out.println("Foo = " + example.getFoo());
// Change its value
example.setFoo(3.1415926);
// See if the change took effect
System.out.println("Foo = " + example.getFoo());
}
}
gcc -dynamiclib -I jni目录 *.c -o libexample.dylib
javac -d . *.java
java test
Ref:
https://www.jianshu.com/p/8d8fdb095f88
https://juejin.cn/post/6844903581095559175