首页 > JAVA/JSP > SWIG Tutorial
2011十二月20

SWIG Tutorial

关于SWIG官方的一个Demo,参见:http://www.swig.org/tutorial.html,有些地方讲解的不是很详细,初次尝试编译的时候,往往编译不通过,下面结合我编译的过程做一个分析。

首先我的编译环境是:

 

root@ithouge-OptiPlex-780:/home/ithouge/Android/jdk1.6.0_23/include/linux# lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 11.04
Release:	11.04
Codename:	natty

gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)

1,新建一个测试用的C文件:/ithouge/test/SWIG/Demo2/example.c

 

#include
 double My_variable = 3.0;
 
 int fact(int n) {
     if (n <= 1) return 1;
     else return n*fact(n-1);
 }
 
 int my_mod(int x, int y) {
     return (x%y);
 }
 
 char *get_time()
 {
     time_t ltime;
     time(<ime);
     return ctime(<ime);
 }

 

2,编写相应的接口文件:/ithouge/test/SWIG/Demo2/example.i

 

/* example.i */
 %module example
 %{
 /* Put header files here or function declarations like below */
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();
 %}
 
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();

 

3,建立java,jni,c模块

首先要确保已经正确安装:swig,可以用以下命令查看。

root@ithouge-OptiPlex-780:/ithouge/test/SWIG/Demo2# swig -version
 
SWIG Version 1.3.40
 
Compiled with g++ [i686-pc-linux-gnu]
Please see http://www.swig.org for reporting bugs and further information
 
root@ithouge-OptiPlex-780:/ithouge/test/SWIG/Demo2# whereis swig
swig: /usr/bin/swig /usr/share/swig1.3 /usr/share/man/man1/swig.1.gz

如果显示信息如上则说明已经安装swig,否则通过apt-get install swig进行安装。

现在,进入到exexample.i所在目录:cd /ithouge/test/SWIG/Demo2

在终端执行:swig -java example.i

执行完成,在当前目录下生成三个新文件:example.java  exampleJNI.java   example_wrap.c

接下来编译.c文件:

 

gcc -c example.c example_wrap.c -I /home/ithouge/Android/jdk1.6.0_23/include/ -I /home/ithouge/Android/jdk1.6.0_23/include/linux/

其中:
/home/ithouge/Android/jdk1.6.0_23/include/ 是jni.h文件所在路径,

查找jni.h所在路径:locate jni.h
/home/ithouge/Android/jdk1.6.0_23/include/linux/ 是jni_mb.h文件所在路径,
执行完以上命令则生成两个.o文件,分别为:example.o  example_wrap.o
最后生成共享库:

 gcc -shared example.o example_wrap.o -o libexample.so

这样在当前目录下生成libexample.so文件,

 

4, 编写java运行程序

至此已经生成动态库,接下来便是编写java程序,实现功能函数。

public class main {
   public static void main(String argv[]) {
//     System.loadLibrary("example");
      System.load("/ithouge/test/SWIG/Demo2/libexample.so");
     System.out.println(example.getMy_variable());
     System.out.println(example.fact(5));
     System.out.println(example.get_time());
   }
 }

System.load/System.loadLibrary作用是加载动态链接库。
之后编译java: javac main.java
运行函数:java main
得到结果如下:

root@ithouge-OptiPlex-780:/ithouge/test/SWIG/Demo2# java main
3.0
120
Tue Dec 20 14:31:20 2011

文章作者:ithouge
本文地址:http://bg135.com/swig-tutorial.html
版权所有 © 转载时必须以链接形式注明作者和原始出处!

本文目前尚无任何评论.

发表评论

3+5= (必填)