---
title: "swig/java"
author: "simplehappy"
date: "2014-02-08T09:51:12Z"
tags: []
categories: ["编程语言"]
slug: "swig-java"
draft: false
lastmod: "2014-02-08T09:51:12Z"
id: 2012226
url: "https://simplehappy.iteye.com/blog/2012226"
---

[摘自  http://www.swig.org/translations/chinese/tutorial.html](http://www.swig.org/translations/chinese/tutorial.html)

 

```
 /* File : example.c */
 
 #include <time.h>
 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(&ltime);
     return ctime(&ltime);
 }
```

 

### 接口文件

```
 /* 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();
```

 

java文件

```
public class main {
   public static void main(String argv[]) {
     System.loadLibrary("example");
     System.out.println(example.getMy_variable());
     System.out.println(example.fact(5));
     System.out.println(example.get_time());
   }
 }
```

 

编译运行:

```
 % swig -java example.i
 % gcc -fpic -c example.c example_wrap.c -I/usr/java/jdk1.4.2/include -I/usr/java/jdk1.4.2/include/linux
 % gcc -shared example.o example_wrap.o -o libexample.so
 % javac main.java
 % java main
 % LD_LIBRARY_PATH=$LD_LIBRARY_PATH:libexample.so所在目录 java main
```