aboutsummaryrefslogtreecommitdiff
path: root/Examples/java/simple/index.html
blob: a363327fedc78f62ead6aad677e4705b824138e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<html>
<head>
<title>SWIG:Examples:java:simple</title>
</head>

<body bgcolor="#ffffff">


<tt>SWIG/Examples/java/simple/</tt>
<hr>

<H2>Simple Java Example</H2>

<p>
This example illustrates how you can hook Java to a very simple C program containing
a function and a global variable.

<h2>The C Code</h2>

Suppose you have the following C code:

<blockquote>
<pre>
/* 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 &gt; 0) {
    g = x;
    x = y % x;
    y = g;
  }
  return g;
}
</pre>
</blockquote>

<h2>The SWIG interface</h2>

Here is a simple SWIG interface file:

<blockquote>
<pre>
/* File: example.i */
%module example

extern int gcd(int x, int y);
extern double Foo;
</pre>
</blockquote>

<h2>Compilation</h2>

<ol>
<li><tt>swig -java <a href="example.i">example.i</a></tt>
<p>
<li>Compile <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.c">example.c</a></tt>
to create the extension <tt>libexample.so (unix)</tt>. 
</ol>

<h2>Using the extension</h2>

Click <a href="main.java">here</a> to see a program that calls our C functions from Java.
<p>
Compile the java files <tt><a href="example.java">example.java</a></tt> and <tt><a href="main.java">main.java</a></tt>
to create the class files example.class and main.class before running main in the JVM.  Ensure that the libexample.so file is in your LD_LIBRARY_PATH before running. For example:
<blockquote>
<pre>
export LD_LIBRARY_PATH=. #ksh 
javac *.java
java main
</pre>
</blockquote>

<h2>Key points</h2>

<ul>
<li>Use the <tt>loadLibrary</tt> statement from java to load and access the generated java classes. For example:
<blockquote>
<pre>
System.loadLibrary("example");
</pre>
</blockquote>

<li>C functions work just like Java functions. For example:
<blockquote>
<pre>
int g = example.gcd(42,105);
</pre>
</blockquote>

<li>C global variables are accessed through get and set functions in the module class. For example:
<blockquote>
<pre>
double a = example.get_Foo();
example.set_Foo(20.0);
</pre>
</blockquote>
</ul>

<hr>
</body>
</html>