实验环境:CentOS 6.7
1. 安装JDK
参考:
2. 编写C函数库
点击(此处)折叠或打开
-
/* 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);
- }
3. 编写SWIG接口文件
点击(此处)折叠或打开
-
/* File : example.i */
-
%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);
4. 生成包装文件,并构建C函数库和包装文件,生成共享库
点击(此处)折叠或打开
- root [ ~/example ]# swig -java example.i
- root [ ~/example ]# gcc -fPIC -c example_wrap.c -I/usr/java/jdk1.8.0_60/include -I/usr/java/jdk1.8.0_60/include/linux
- root [ ~/example ]# gcc -fPIC -c example.c
- root [ ~/example ]# ld -G example_wrap.o example.o -o libexample.so
5. 编写Java程序调用C函数库
点击(此处)折叠或打开
-
// runme.java
-
-
public class runme {
-
static {
-
System.loadLibrary("example");
-
}
-
-
public static void main(String argv[]) {
-
System.out.println("fact(4) = " + example.fact(4));
-
System.out.println("my_mod(7, 2) = " + example.my_mod(7, 2));
-
}
- }
6. 编译所有Java源文件并运行
点击(此处)折叠或打开
- root [ ~/example ]# javac *.java
- root [ ~/example ]# java runme
- fact(4) = 24
- my_mod(7, 2) = 1