PageRenderTime 22ms CodeModel.GetById 16ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/rel-1.3.35/Examples/java/simple/index.html

#
HTML | 108 lines | 85 code | 23 blank | 0 comment | 0 complexity | 2f8eff968fd87721a62f4bbcedd12618 MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0
  1<html>
  2<head>
  3<title>SWIG:Examples:java:simple</title>
  4</head>
  5
  6<body bgcolor="#ffffff">
  7
  8
  9<tt>SWIG/Examples/java/simple/</tt>
 10<hr>
 11
 12<H2>Simple Java Example</H2>
 13
 14<p>
 15This example illustrates how you can hook Java to a very simple C program containing
 16a function and a global variable.
 17
 18<h2>The C Code</h2>
 19
 20Suppose you have the following C code:
 21
 22<blockquote>
 23<pre>
 24/* File : example.c */
 25
 26/* A global variable */
 27double Foo = 3.0;
 28
 29/* Compute the greatest common divisor of positive integers */
 30int gcd(int x, int y) {
 31  int g;
 32  g = y;
 33  while (x &gt; 0) {
 34    g = x;
 35    x = y % x;
 36    y = g;
 37  }
 38  return g;
 39}
 40</pre>
 41</blockquote>
 42
 43<h2>The SWIG interface</h2>
 44
 45Here is a simple SWIG interface file:
 46
 47<blockquote>
 48<pre>
 49/* File: example.i */
 50%module example
 51
 52extern int gcd(int x, int y);
 53extern double Foo;
 54</pre>
 55</blockquote>
 56
 57<h2>Compilation</h2>
 58
 59<ol>
 60<li><tt>swig -java <a href="example.i">example.i</a></tt>
 61<p>
 62<li>Compile <tt><a href="example_wrap.c">example_wrap.c</a></tt> and <tt><a href="example.c">example.c</a></tt>
 63to create the extension <tt>libexample.so (unix)</tt>. 
 64</ol>
 65
 66<h2>Using the extension</h2>
 67
 68Click <a href="main.java">here</a> to see a program that calls our C functions from Java.
 69<p>
 70Compile the java files <tt><a href="example.java">example.java</a></tt> and <tt><a href="main.java">main.java</a></tt>
 71to 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:
 72<blockquote>
 73<pre>
 74export LD_LIBRARY_PATH=. #ksh 
 75javac *.java
 76java main
 77</pre>
 78</blockquote>
 79
 80<h2>Key points</h2>
 81
 82<ul>
 83<li>Use the <tt>loadLibrary</tt> statement from java to load and access the generated java classes. For example:
 84<blockquote>
 85<pre>
 86System.loadLibrary("example");
 87</pre>
 88</blockquote>
 89
 90<li>C functions work just like Java functions. For example:
 91<blockquote>
 92<pre>
 93int g = example.gcd(42,105);
 94</pre>
 95</blockquote>
 96
 97<li>C global variables are accessed through get and set functions in the module class. For example:
 98<blockquote>
 99<pre>
100double a = example.get_Foo();
101example.set_Foo(20.0);
102</pre>
103</blockquote>
104</ul>
105
106<hr>
107</body>
108</html>