Chinaunix首页 | 论坛 | 博客
  • 博客访问: 235748
  • 博文数量: 21
  • 博客积分: 796
  • 博客等级: 军士长
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-16 01:03
文章分类
文章存档

2020年(1)

2017年(1)

2016年(1)

2015年(2)

2012年(9)

2011年(7)

我的朋友

分类: LINUX

2015-12-03 23:11:45


实验环境:CentOS 6.7

1. 安装JDK
参考:

2. 编写C函数库

点击(此处)折叠或打开

  1. /* File : example.c */

  2. double My_variable = 3.0;

  3. /* Compute factorial of n */
  4. int fact(int n) {
  5.   if (n <= 1) return 1;
  6.   else return n*fact(n-1);
  7. }

  8. /* Compute n mod m */
  9. int my_mod(int n, int m) {
  10.   return(n % m);
  11. }

3. 编写SWIG接口文件

点击(此处)折叠或打开

  1. /* File : example.i */
  2. %module example
  3. %{
  4.   /* Put headers and other declarations here */
  5.   extern double My_variable;
  6.   extern int fact(int);
  7.   extern int my_mod(int n, int m);
  8.   %}

  9. extern double My_variable;
  10. extern int fact(int);
  11. extern int my_mod(int n, int m);

4. 生成包装文件,并构建C函数库和包装文件,生成共享库

点击(此处)折叠或打开

  1. root [ ~/example ]# swig -java example.i
  2. 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
  3. root [ ~/example ]# gcc -fPIC -c example.c
  4. root [ ~/example ]# ld -G example_wrap.o example.o -o libexample.so

5. 编写Java程序调用C函数库

点击(此处)折叠或打开

  1. // runme.java

  2. public class runme {
  3.   static {
  4.     System.loadLibrary("example");
  5.   }

  6.   public static void main(String argv[]) {
  7.     System.out.println("fact(4) = " + example.fact(4));
  8.     System.out.println("my_mod(7, 2) = " + example.my_mod(7, 2));
  9.   }
  10. }

6. 编译所有Java源文件并运行

点击(此处)折叠或打开

  1. root [ ~/example ]# javac *.java
  2. root [ ~/example ]# java runme
  3. fact(4) = 24
  4. my_mod(7, 2) = 1

阅读(2728) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~