<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>jni &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/jni/</link>
	<description>Feed of posts on WordPress.com tagged "jni"</description>
	<pubDate>Sat, 26 Jul 2008 18:10:04 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[JNI - Eclipse + CDT + MinGW]]></title>
<link>http://zenedith.wordpress.com/?p=39</link>
<pubDate>Wed, 23 Jul 2008 20:40:22 +0000</pubDate>
<dc:creator>zenedith</dc:creator>
<guid>http://zenedith.wordpress.com/?p=39</guid>
<description><![CDATA[Pisałem już o różnych językach skryptowych - postaram się opisać przynajmniej podstawy wspó]]></description>
<content:encoded><![CDATA[<p>Pisałem już o różnych językach skryptowych - postaram się opisać przynajmniej podstawy współpracy z cpp z każdym z nich. Dziś przedstawię jak wygląda współpraca Javy i cpp przez interfejs <em>JNI (Java Native Interface)</em>.</p>
<p>Tak jak w temacie, pokażę jak napisać prosty pomost między Javą a cpp przy wykorzystaniu IDE <em>Eclipse </em>z biblioteką <em><a href="http://www.eclipse.org/cdt/" target="_blank">CDT5.0</a></em> oraz wykorzystując toolchain'a <em>MinGW</em>. O sposobie konfiguracji takiego środowiska wspomniałem już <a href="http://zenedith.wordpress.com/2008/07/02/cpp-ide-eclipse-mingw/">wcześniej</a>, a więc zaczynamy.</p>
<p>Naszym zadaniem będzie napisanie kodu w Javie, który będzie wykorzystywał dll'ke, którą przygotujemy wykorzystując język cpp i toolchain'a <em>MinGW </em>- będziemy przesyłać i odbierać dane z dll'a.</p>
<p>Lista wymagań jest następująca:</p>
<ol>
<li><em>Eclipse + CDT + MinGW</em>,</li>
<li><em>Java JDK</em> (nie musi być koniecznie nowe), <em>JRE </em>nie wystarczy.</li>
</ol>
<p>Ze wspomnianego <em>JDK </em>wykorzystamy następujące rzeczy:</p>
<ul>
<li><strong>bin\javah.exe</strong> - pozwoli automatycznie wygenerować nagłówek języka cpp(.h) dla danej klasy Javy,</li>
<li><strong>include\jni.h</strong> - dostarcza "funkcje" do konwersji typów Java &#60;-&#62; cpp oraz wiele innych,</li>
<li><strong>include\</strong>$<em>platform</em>$ - $<em>platform</em>$ w moim przypadku to win32.</li>
</ul>
<p>Kolejne kroki które będziemy wykonywać przedstawiają się następująco:</p>
<ol>
<li>napisanie kodu klas(y) w Javie z użyciem słowa kluczowego <strong>native</strong>,</li>
<li>kompilacja klas(y) - otrzymujemy pliki .<em>class</em>,</li>
<li>wygenerowanie nagłówka dla języka cpp (.h) za pomocą narzędzia <strong>javah.exe</strong>,</li>
<li>implementacja wygenerowanego pliku nagłówkowego w projekcie w języku cpp,</li>
<li>skompilowanie kodu do postaci pliku biblioteki dynamicznej (dll/so),</li>
<li>uruchomienie aplikacji Javy.</li>
</ol>
<p>Zaczynamy - punkt 1 i napisanie kodu klasy w Javie.<br />
Jak już wspomniałem, użyjemy słowa kluczowego <strong>native</strong> do oznaczenia metod, które chcielibyśmy zaimplementować w języku cpp.</p>
<p>Niech za przykład takiego kodu w Javie posłuży nam następująca klasa:</p>
<p>public class SomeData {</p>
<p style="padding-left:30px;">native String GetVersion();<br />
native void SetVersion(String sNewVersion);<br />
native void DoSomething();</p>
<p style="padding-left:30px;">static{</p>
<p style="padding-left:60px;">System.loadLibrary("libjni_test");</p>
<p style="padding-left:30px;">}</p>
<p style="padding-left:30px;">public String GetSomeDataFromJava(){</p>
<p style="padding-left:60px;">return "dane z javy";</p>
<p style="padding-left:30px;">}</p>
<p style="padding-left:30px;">public static void main(String[] args) {</p>
<p style="padding-left:60px;">SomeData cData = new SomeData();<br />
System.out.println("Version: "+cData.GetVersion());</p>
<p style="padding-left:30px;">}</p>
<p>}</p>
<p>Parę słów komentarza: na początku mamy metody natywne, które będziemy implementować w cpp - podajemy więc ich definicję i na tym kończymy. Następnie widoczny jest blok static{} w którym podajemy informację do <em>JVM</em>, z jakiej dokładnie biblioteki dll/so będziemy korzystać.<br />
Ważne są dwie rzeczy:</p>
<ol>
<li><strong>nie podajemy tam rozszerzenia pliku</strong> (bez dll/so) ponieważ w zależności od systemu <em>JVM </em>zrobi to za nas,</li>
<li><strong>nie musimy ładowania biblioteki zewnętrznej umieszczać w bloku static{} </strong>- równie dobrze można to zrobić zaraz na początku metody <em>main(String[] args)</em>.</li>
</ol>
<p>Ostatecznie w metodzie <em>main(String[] args)</em> wywołujemy naszą natywną metodę w celu sprawdzenia efektu.</p>
<p>Czas na punkt 2 z listy czyli kompilację - tak naprawdę dzieje się ona z automatu jeśli mamy w <em>Eclipse</em> ustawioną opcję automatycznego kompilowania przy zapisywaniu pliku. Jeśli więc utworzyliśmy prosty projekt Javy, to plik źródłowy (.<em>java</em>) znajduje się w katalogu <strong>/src/</strong> a skompilowana klasa w katalogu <strong>/bin/</strong>.</p>
<p>W punkcie następnym użyjemy generatora nagłowka (.h) - narzędzia <em>javah.exe</em>. Jeśli jest on w naszej zmiennej środowiskowej <em>PATH </em>to wydanie polecania:</p>
<p><strong>javah -jni <em>$nasza_klasa$</em></strong></p>
<p>w katalogu <strong>\src\</strong> powinno zakończyć się sukcesem i wygenerowanym nagłówkiem, lecz może być jeszcze konieczne przekopiowanie pliku skompilowanego (.<em>class</em>) z katalogu <strong>\bin\</strong> do <strong>\src\</strong>.<br />
Natomiast jeśli wydanie powyższego polecania zgłasza błąd nieznanego polecenia, należy edytować zmienną <em>PATH </em>(np. z poziomu właściwości mój komputer, na zakładce Zaawansowane, przycisk zmienne środowiskowe, dodając dodatkowy wpis do zmiennej <em>PATH</em>, który będzie zawierał ścieżkę do pliku wykonywalnego <em>java, javac, javah, itp.</em> - np. <em>D:\Program Files\Java\jdk1.6.0_06\bin\</em> - <strong>należy uważać żeby nie nadpisać jej całkowicie a tylko dopisać</strong> dodając średnik jeśli to konieczne do oddzielenia ścieżek).</p>
<p>W tym momencie mamy już wygenerowany plik nagłówkowy więc możemy w <em>Eclipse</em> opcjonalnie przełączyć perspektywę na C/C++ i utworzyć projekt C++ (<strong>New C++ Project</strong>) - również pisałem już o tym <a href="http://zenedith.wordpress.com/2008/07/02/cpp-ide-eclipse-mingw/">wcześniej</a>, najważniejsze żeby dostępny był toolchain <em>MinGW </em>oraz rodzaj projektu wybrać <em>Empty Project </em>(.exe) ewentualnie docelowy <em>Shared Library</em>.</p>
<p><a href="http://zenedith.wordpress.com/files/2008/07/perspective.jpg"><img src="http://zenedith.wordpress.com/files/2008/07/perspective.jpg?w=128" alt="" width="128" height="77" class="alignnone size-thumbnail wp-image-49" /></a>   <a href="http://zenedith.wordpress.com/files/2008/07/new_cpp_project.jpg"><img src="http://zenedith.wordpress.com/files/2008/07/new_cpp_project.jpg?w=128" alt="" width="128" height="76" class="alignnone size-thumbnail wp-image-50" /></a>   <a href="http://zenedith.wordpress.com/files/2008/07/project_type.jpg"><img src="http://zenedith.wordpress.com/files/2008/07/project_type.jpg?w=86" alt="" width="86" height="96" class="alignnone size-thumbnail wp-image-51" /></a></p>
<p>Po utworzeniu pustego projektu, należy dokonać na starcie paru ustawień - przechodzimy do jego właściwości:</p>
<ul>
<li>na zakładce <strong>C/C++ Bulid</strong> przechodzimy do <strong>Settings/Tool Settings</strong>,</li>
<li>przechodzimy do <strong>GCC C++ Compiler</strong> i dalej do <strong>Directories</strong>,</li>
<li>klikając przycisk dodajemy katalogi <strong>\include</strong> i <strong>\include\win32</strong> - (w moim przypadku są to <em>D:\Program Files\Java\jdk1.6.0_06\include</em> oraz <em>D:\Program Files\Java\jdk1.6.0_06\include\win32</em>)</li>
<li>zatwierdzamy wprowadzone zmiany,</li>
<li>następnie odnajdujemy zakładkę <strong>MinGW C++ Linker</strong>, która jest na poziomie <strong>C/C++ Bulid</strong>,</li>
<li>przechodzimy do zakładki <strong>Miscellaneous </strong>i w <strong>Linker Flags</strong> wpisujemy:<br />
<strong>-Wl,--add-stdcall-alias</strong><br />
<strong>Bardzo istotna opcja</strong>, ponieważ dzięki niej nie dojdzie do "udziwnienie" metod w wynikowym pliku biblioteki dynamicznej. Gdybyśmy o tej opcji zapomnieli, to pomimo że nasza biblioteka byłaby widoczna, to <em>JVM </em>nie odnalazłaby w niej określonych nazw, właśnie przez te "udziwnienia", tworzone przez linker z toolchain'a <em>MinGW</em>.</li>
<li>sprawdzamy jeszcze, czy na zakładce poniżej <strong>Miscellaneous-Shared Library Settings</strong> zaznaczona jest pierwsza opcja od góry <strong>Shared</strong> (jeśli tworzony był <em>Empty Project </em>trzeba ją zaznaczyć),</li>
<li>opcjonalnie, jeśli korzystaliśmy z <em>Empty Project </em>musimy zmienić ustawienia generowania pliku wykonywalnego na generowania dll/so - uczynimy to zmieniając zakładkę <strong>Tool Settings</strong> na <strong>Build Artifact</strong> i ustawiając pole <strong>Artifact Type</strong> na <strong>Shared Library</strong>. Resztę opcji możemy tak pozostawić chyba że pragniemy dla przykładu nadać jakąś specyficzną nazwę dla biblioteki dynamicznej.</li>
<li>zatwierdzamy wprowadzone zmiany i powracamy do ekranu głównego.</li>
</ul>
<p><a href="http://zenedith.wordpress.com/files/2008/07/properties.jpg"><img src="http://zenedith.wordpress.com/files/2008/07/properties.jpg?w=56" alt="" width="56" height="96" class="alignnone size-thumbnail wp-image-53" /></a>  <a href="http://zenedith.wordpress.com/files/2008/07/tools_settings.jpg"><img src="http://zenedith.wordpress.com/files/2008/07/tools_settings.jpg?w=102" alt="" width="102" height="96" class="alignnone size-thumbnail wp-image-54" /></a>   <a href="http://zenedith.wordpress.com/files/2008/07/artifact1.jpg"><img src="http://zenedith.wordpress.com/files/2008/07/artifact1.jpg?w=102" alt="" width="102" height="96" class="alignnone size-thumbnail wp-image-56" /></a></p>
<p>Teraz możemy zaimportować wygenerowany przez javah plik nagłówkowy (<em>import/File System/</em>podajemy scieżkę do wygenerowanego pliku nagłówkowego). Gdy spróbujemy ten plik podejrzeć,  include jni.h nie powinien zgłaszać błędów (w p.p sprawdź <em>include directory</em>), lecz syntax error'y pojawią się przy wszystkich liniach rozpoczynających się np. tak <em>JNIEXPORT jstring JNICALL</em>, czyli wszystkich eksportowanych metodach z/do Javy - nie musimy się tym w ogóle przejmować.</p>
<p>Teraz należy utworzyć plik implementacji zaimportowanego pliku nagłówkowego czyli wkraczamy w punkt 4 - dodajemy w nim include'y dla pliku nagłówkowego i jni.h oraz kopiujemy definicje metod z pliku nagłówkowego i uzupełniamy je o nazwy zmiennych w metodach(są tylko typy) oraz ciało metod.</p>
<p>Dla przykładu podam ciało metody zwracającej z dll'ki napis typu String:<br />
<code><br />
JNIEXPORT jstring JNICALL Java_SomeData_GetVersion(JNIEnv * env, jobject o){<br />
const char *str = "1.1 MinGW compiled";<br />
return env-&#62;NewStringUTF(str);<br />
}</code></p>
<p>Jak widać w powyższym, nie ma bezpośredniej konwersji typów między Javą i cpp, dlatego musimy się posługiwać metodami konwersji, które dostępne są przez odwołanie do <em>JNIEnv</em>, która jest tablicą metod pomocniczych.</p>
<p>Kompilujemy kod (<strong>Bulid Project</strong>) i jeśli wszystko dobrze wcześniej ustawiliśmy, otrzymamy w wyniku plik biblioteki dynamicznej o nazwie projektu z przedrostkiem lib lub podaną przy ustawieniach <em>Arifact name</em>, co kończy punkt 5.</p>
<p>Przed wykonaniem ostatniego punktu, czyli odpalenia aplikacji Javy, musimy w odpowiednim miejscu umieścić nasz plik wynikowy biblioteki dynamicznej. Możemy go umieścić w scieżkę wskazywanej przez <em>java.library.path</em> lub umieścić w wybranym miejscu i w ustawieniach projektu Javy - <strong>Java Build Path</strong>, rozwinąć zakładkę <strong>Source </strong>i edytować ostatnią pozycję o nazwie <strong>Native Library Location</strong>, wskazując folder gdzie znajduje się skompilowany dll/so.</p>
<p>Czas na wykonanie ostatniego kroku i uruchomienie (najszybciej w Eclipse z opcji Run As/Java application) kodu. W wyniku nie powinniśmy otrzymać błędu <strong>java.lang.UnsatisfiedLinkError</strong>, a jeśli się to zdarzy, to należy uważnie przejrzeć opisane wcześniej czynności.</p>
<p>W ten sposób kończę ten najdłuższy do tej pory wpis na blogu. Postaram się dodać screeny z poszczególnych ustawień opcji, aby rozwiać wszelkie wątpliwości.</p>
<p>Z takimi podstawami można już szybko ruszyć w dalszą drogę i poznawać możliwości <em>JNI</em>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Call native C/C++ functions from Java using JNI]]></title>
<link>http://developerspoint.wordpress.com/?p=42</link>
<pubDate>Sat, 21 Jun 2008 17:04:37 +0000</pubDate>
<dc:creator>prajwalan</dc:creator>
<guid>http://developerspoint.wordpress.com/?p=42</guid>
<description><![CDATA[The Java Native Interface (JNI) is a programming framework that allows Java code running in the Java]]></description>
<content:encoded><![CDATA[<p>The Java Native Interface (JNI) is a programming framework that allows Java code running in the Java virtual machine (JVM) to call and be called by native applications (programs specific to a hardware and operating system platform) and libraries written in other languages, such as C, C++ and assembly.</p>
<p>The JNI is used to write native methods to handle situations when an application cannot be written entirely in the Java programming language such as when the standard Java class library does not support the platform-specific features or program library. It is also used to modify an existing application, written in another programming language, to be accessible to Java applications. Many of the standard library classes depend on the JNI to provide functionality to the developer and the user, e.g. I/O file reading and sound capabilities. Including performance- and platform-sensitive API implementations in the standard library allows all Java applications to access this functionality in a safe and platform-independent manner.</p>
<p>The JNI is not trivial and requires a considerable effort to learn, and some people recommend that only advanced programmers should use the JNI. However, the capability for Java to communicate with C++ and assembly removes any limitations on what function Java programs can perform. Programmers considering using the JNI should be aware that</p>
<p>   1. JNI is not an easy API to learn;<br />
   2. Subtle errors in the use of JNI can destabilize the entire JVM in ways that are very difficult to reproduce and debug;<br />
   3. Only applications and signed applets can invoke the JNI;<br />
   4. An application that relies on JNI loses the platform portability Java offers (a workaround is to write a separate implementation of the JNI code for each platform and have Java detect the Operating System and load the correct one at runtime);<br />
   5. There is no garbage collection for the JNI side (JNI code must do explicit deallocation);<br />
   6. Error checking is a MUST or it has the potential to crash the JNI side and the JVM.</p>
<p>Enough of boring stuff. Now lets see some codes.</p>
<p>Here we will try to call the MFC function AfxMessageBox() from Java. Our function in C++ will take no arguments and will not return any value.</p>
<p>Following a simple Java program that calls the method showMessageBox() defined in a DLL, which we will create later.</p>
<pre><code>public class JNISample
{
    static
    {
        System.loadLibrary("TestDll");
    }
    public static void main(String[] arg)
    {
        System.out.println("Hello world from Java");
        JNISample t =new JNISample();
        t.showMessageBox();
    }
    public native void showMessageBox();
}</code></pre>
<p>As we can see, we have loaded a DLL, which we will soon create in Visual C++. This DLL consists of a method showMessageBox() which is defined in C++. This a basic procedure of using JNI. We write our application in Java first and declare the methods that will be required to call. We rarely write the native code first.</p>
<p>An alternative way to load a DLL will be to use System.load(...) method. With this load() method, you can supply any path to the DLL. While, the one used above i.e. loadLibrary(...) requires the DLL to be in the &#60;WinDIR&#62;\system32 folder.</p>
<p>Now the next step will be to generate a header file corresponding to this class. We use javah.exe utility which is included with JDK.</p>
<pre><code>javah -jni JNISample</code></pre>
<p>This will generate a header file. We will need this header file during the next step.</p>
<p>Now we are need to write a DLL which will contain the implementation of our native function. Easiest way is to use MFC AppWizard (DLL). Lets name the project TestDll. We should also include the header file we generate previously in TestDll.h.</p>
<p>Then, lets copy following line from JNISample.h and paste it at the end of TestDll.h.</p>
<pre><code>JNIEXPORT void JNICALL Java_JNISample_showMessageBox(JNIEnv *, jobject);</code></pre>
<p>and add following definition in the implementation file:</p>
<pre><code>JNIEXPORT void JNICALL Java_JNISample_showMessageBox(JNIEnv *env, jobject obj)
{
    AfxMessageBox("MFC Hello via. a DLL");
}</code></pre>
<p>Before we compile this application, we should include the path of jni.h header file. So following two directories should included through the IDE settings.<br />
&#60;JDK DIR&#62;\include<br />
&#60;JDK DIR&#62;\include\win32 </p>
<p>Now lets compile and generate our DLL, put newly created DLL in system32 directory and then run our class file to see the output.</p>
<p><em>Credit: Initial description of JNI was taken from Wikipedia.</em></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Getting a Class Started with JNI, Part 4: Writing Native Methods]]></title>
<link>http://combativecoder.wordpress.com/?p=26</link>
<pubDate>Thu, 19 Jun 2008 07:06:31 +0000</pubDate>
<dc:creator>John Moeller</dc:creator>
<guid>http://combativecoder.wordpress.com/?p=26</guid>
<description><![CDATA[Up to now, I&#8217;ve talked about how to get the skeleton of your class working.  That&#8217;s all ]]></description>
<content:encoded><![CDATA[<p><a href="2008/06/09/getting-a-class-started-with-jni-part-1-scaffolding/">Up</a> <a href="2008/06/11/getting-a-class-started-with-jni-part-2-native-methods-using-javah/">to</a> <a href="2008/06/15/getting-a-class-started-with-jni-part-3-native-methods-using-registernatives/">now</a>, I've talked about how to get the skeleton of your class working.  That's all fine, but you'll find that even if you're just wrapping a native library, you won't know how to handle any state that needs to go back and forth.  </p>
<p>Almost all native libraries have some kind of nugget of data that represents state.  It's often the return value from some factory function and the first argument of every other function in the API, and it's almost always a pointer.  You'll find this model in many stable libraries because it scales incredibly well.<br />
<!--more--><br />
We'll get to the state itself later on.  For now, assume that we have it, and that it's held by a pointer. <a href="#bk1" name="fn1" title="Footnote 1">[1]</a></p>
<h4>KISS</h4>
<p>In case you've been living under a rock, this annoying acronym stands for "<em><strong>K</strong>eep <strong>I</strong>t <strong>S</strong>imple, <strong>S</strong>tupid.</em>"  Whether you decide to take it as a personal insult is your choice, but it's a good principle to adhere to when you design a native interface.  What this means is that you should keep complexity in your native interface to a minimum.  </p>
<p>If you're just wrapping a stable native library, wrap the API functions that you need and no more.  Don't try to get fancy with the API anywhere between the <strong><tt>native</tt></strong> method and the actual API functions.  Wrap it as minimally as you can.  If it's a good library, the authors will have designed it well.  Don't mess with it.  If you want to get fancy, you can do that on the <em>other</em> side of the class that has the <strong><tt>native</tt></strong> methods.</p>
<p>If you're delegating some part of your class to a native library, the same principle applies.  Keep the interface minimal.  Trust me when I say that you won't be served well by an ill-planned, overly-complicated interface.  Leave the complexity to the implementation of the library.  </p>
<p>One last thing to consider is performance.  I'm not talking about premature optimization.  I'm talking about preventing premature "pessimization."  Be judicious in the design of your interface.  For example, if you've got an operation that does the same thing to a bunch of pixels, don't design a <strong><tt>native</tt></strong> method that operates on one pixel.  You wouldn't design your Java class or native API that way, so don't do it across the boundary, either.  There are structures in JNI that help with passing large volumes of data around.  Use them.</p>
<h4>Representing your native data nugget</h4>
<p>I already asked you to assume that you're using a pointer to represent your state.  There are a number of complicated ways to encapsulate this idea on the Java side.  You could create a "mirror" object, or you could encapsulate the idea of a pointer in a "Pointer" class.  Both those methods add a needless layer of complexity.  Use them, but don't pass them across the native/Java boundary.  Remember: simple.</p>
<p>So what's the simplest way to represent a pointer in Java?  A pointer is essentially just a number. <a href="#bk2" name="fn2" title="Footnote 2">[2]</a>  Easy enough.  Just return a <strong><tt>jlong</tt></strong> and pass that around.  You should do that.  But there's a problem.</p>
<p>It's intrinsic to the effort.  Native code (usually) requires explicit resource management, via a dispose() or free() API function.  Java uses GC.  So you have to treat native state like you would a network connection.  You need to release the resource when you don't need it.  That means that you always need a cleanup <strong><tt>native</tt></strong> method, and you need to be disciplined about resource usage.  The <strong><tt>try/finally</tt></strong> way of handling this is often a good methodology.</p>
<p>The reasoning here is that sometimes native state can represent a significant expenditure of heap memory or other resources.  In fact, the native state may hang on to network connections, keeping them open until the disposal function is called.  You just don't know.  It's a good idea to work within the native resource model, and release the resource as soon as you're finished with it.  In fact, I don't like depending on a finalizer at all, and avoid implementing them, at least to manage resources. <a href="#bk3" name="fn3" title="Footnote 3">[3]</a></p>
<h4>Declare <strong><tt>native</tt></strong> methods as <strong><tt>static</tt></strong></h4>
<p>It's natural, if you've been steeped in OOP, to think that for any native method that passes state, you should declare it as a member of the class.  I claim that it's more useful to declare each native method as static.  Let's compare.  Here's the two ways to declare essentially the same thing:</p>
<p>[sourcecode language='java']...<br />
  private native boolean doSomething<br />
    (long ptr, double x, double y);<br />
  private static native boolean doSomething<br />
    (NativeClass obj, long ptr, double x, double y);<br />
...[/sourcecode]</p>
<p>And here's what you end up with on the native side:</p>
<p>[sourcecode language='cpp']...<br />
jboolean doSomething_member<br />
  (JNIEnv *env, jobject obj, jlong ptr,<br />
  jdouble x, jdouble y)<br />
{<br />
  ...<br />
}</p>
<p>jboolean doSomething_static<br />
  (JNIEnv *env, jclass cls, jobject obj, jlong ptr,<br />
  jdouble x, jdouble y)<br />
{<br />
  ...<br />
}<br />
...[/sourcecode]</p>
<p>It's slightly longer, because you have to pass <strong><tt>this</tt></strong> as the first parameter, and then the native pointer, but it has a hidden parameter that's useful: the class.  If you declared the method as non-static, then you'd have to look up this information inside the native implementation.  Declaring as static prevents the need for the lookup.</p>
<h4>Declare <strong><tt>native</tt></strong> methods as <strong><tt>private</tt></strong></h4>
<p>Additionally, you'll notice that I declared the native methods as <strong><tt>private</tt></strong>.  I need to pass the pointer parameter every time I call a method, but I don't need that implementation detail exposed to the world.  So I just create a wrapper function that calls the native method with the state pointer, and make the state pointer private as well.  If I do this, though, it doesn't matter if I declare the native method as static or not.  If it's all wrapped up anyway, just make it static and no one has to care that <strong><tt>this</tt></strong> has to be passed as a parameter.</p>
<h4>Taking it from here</h4>
<p>And that's my advice for creating a native library.  At this point, it's pretty much all implementation.  I hope you find it useful.  Be sure to check out <a href="category/jni-tutorial/">parts 1-3</a>.  I also plan to do a walk-through of wrapping a native library, to give an idea of how it all goes together.</p>
<p><a href="http://digg.com/submit?url=http%3A%2F%2Fcombativecoder.wordpress.com%2F2008%2F06%2F19%2Fgetting-a-class-started-with-jni-part-4-writing-native-methods&#38;title=Getting%20a%20Class%20Started%20with%20JNI%2C%20Part%204%3A%20Writing%20Native%20Methods&#38;topic=programming"><img src="http://digg.com/img/badges/100x20-digg-button.gif" width="100" height="20" alt="Digg!" style="border:none;" /></a> <a href="http://reddit.com/submit?url=http%3A%2F%2Fcombativecoder.wordpress.com%2F2008%2F06%2F19%2Fgetting-a-class-started-with-jni-part-4-writing-native-methods&#38;title=Getting%20a%20Class%20Started%20with%20JNI%2C%20Part%204%3A%20Writing%20Native%20Methods"><img src="http://s3.amazonaws.com/sp.reddit.com/reddit80x15b.gif" alt="Reddit This" style="border:none;" /></a></p>
<h4>Footnotes:</h4>
<p><a href="#fn1" name="bk1" title="Footnote 1">[1]</a> So why don't we address working with Java state the same way?  The reason is that native-to-Java calls can be slower than Java-to-native calls by a nontrivial amount.  In my testing, Java-to-native calls have negligible cost.  My guess is that these calls are optimized because they're the important part of native libraries.  Whether you're taking advantage of an existing native library or trying to gain performance in Java code, you're delegating work to the native side.</p>
<p><a href="#fn2" name="bk2" title="Footnote 2">[2]</a> C++ mavens might chime in at this point and explain that a pointer isn't always a number.  But you can always get a unique numeric representation of a pointer, which is the important part.</p>
<p><a href="#fn3" name="bk3" title="Footnote 3">[3]</a> You may be thinking that a "Pointer" class is a good idea at this point.  It's not necessarily a <em>bad</em> idea, but you should still provide an explicit "dispose" method that does the job of releasing the resources, and not just depend on the finalizer to take care of it.  </p>
<p>Tags: <a href="http://technorati.com/tag/JNI" rel="tag">JNI</a>, <a href="http://technorati.com/tag/Java" rel="tag">Java</a>, <a href="http://technorati.com/tag/DLL" rel="tag">DLL</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JNI - Calling C/C++ code from Java programs]]></title>
<link>http://ramanauppala.wordpress.com/?p=4</link>
<pubDate>Mon, 16 Jun 2008 08:50:18 +0000</pubDate>
<dc:creator>ramanauppala</dc:creator>
<guid>http://ramanauppala.wordpress.com/?p=4</guid>
<description><![CDATA[To access a library routine from a Java program, I use the Java SDK&#8217;s Java Native Interface (J]]></description>
<content:encoded><![CDATA[<p>To access a library routine from a Java program, I use the Java SDK's Java Native Interface (JNI), which gives compile- and run-time support for calling native code from a Java program. By native code, I mean code that is not Java, typically C or C++;</p>
<p>At compile time, JNI defines how Java data types correspond to C data types. C programs get this information from JNI header files that come with the Java SDK. Javah, a tool that comes with the SDK, creates application-specific header files that help eliminate programming errors in communication between Java and C routines. At run time, JNI lets Java objects be passed to C code, and lets C code access Java properties and methods. Thus, C code can set properties of Java classes, making it possible to call Java methods from C.</p>
<p><a name="N101D3"><span class="smalltitle">Six steps to call C/C++ from Java code</span></a></p>
<p>The process of calling C or C ++ from Java programs consists of six steps. We'll go over each step in depth in the sections that follow, but let's start with a quick look at each one.</p>
<p> </p>
<ol>
<li><strong>Write the Java code</strong>. We'll start by writing Java classes to perform three tasks: declare the native method we'll be calling; load the shared library containing the native code; and call the native method.</li>
<li><strong>Compile the Java code</strong>. We must successfully compile the Java class or classes to bytecode before we can use them.</li>
<li><strong>Create the C/C++ header file</strong>. The C/C++ header file will declare the native function signature that we want to call. This header will then be used with the C/C++ function implementation (see Step 4) to create the shared library (see Step 5).</li>
<li><strong>Write the C/C++ code</strong>. This step consists of implementing the function in a C or C++ source code file. The C/C++ source file must include the header file we created in Step 3.</li>
<li><strong>Create the shared library file</strong>. We'll create a shared library file from the C source code file we created in Step 4.</li>
<li><strong>Run the Java program</strong>. We'll run the code and see if it works. We'll also go over some tips for dealing with the more commonly occurring errors.</li>
</ol>
<p> </p>
<p> </p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Getting a Class Started with JNI, Part 3: Native Methods Using RegisterNatives]]></title>
<link>http://combativecoder.wordpress.com/?p=23</link>
<pubDate>Sun, 15 Jun 2008 06:15:56 +0000</pubDate>
<dc:creator>John Moeller</dc:creator>
<guid>http://combativecoder.wordpress.com/?p=23</guid>
<description><![CDATA[In part 2, I talked about using javah to set up native implementation functions.  In this post, I]]></description>
<content:encoded><![CDATA[<p>In <a href="2008/06/11/getting-a-class-started-with-jni-part-2-native-methods-using-javah/">part 2</a>, I talked about using <strong><em>javah</em></strong> to set up native implementation functions.  In this post, I'll talk about how to use a different method to set up the native method linkage.</p>
<p>Let me reiterate what I see as the pros and cons of <strong><em>javah</em></strong>:<br />
<!--more--></p>
<h4>Pros:</h4>
<ol>
<li>Simple; you only have to run a command and the declarations are done</li>
<li>Great for whipping up a wrapper interface for a stable native library</li>
</ol>
<h4>Cons:</h4>
<ol>
<li>Changes in the Java interface can have unexpected results</li>
<li>Signature encoding for overloaded functions is odd and different from the encoding for the rest of the API</li>
<li>It exposes the native interface to the world</li>
</ol>
<p>There's another way to get the job done, and it essentially inverts these arguments.  That is, this method takes a little more effort to get started, and it's not ideal for throwing together a quick wrapper.  However, if you invert the cons above, they become pros for this method.  What method is this?  <strong><tt>RegisterNatives</tt></strong>.</p>
<p>With <strong><tt>RegisterNatives</tt></strong>, you essentially take a class, and a map (a mapping is the name of a method and the Java signature of the method, and a function pointer to a native implementation) and you tell the JVM to use that map for the class.</p>
<ul>
<li>
<h4>The encoding is the same as the rest of the API:</h4>
<p>The bad news here is that you can't generate the map automatically. <a href="#fn1" name="bk1" title="Footnote 1">[1]</a>   The good news is that Java method signatures are easily found by using <strong><em>javap</em></strong> (they're also listed in the comments in the header that <strong><em>javah</em></strong> creates).  The <strong><em>javap</em></strong> program is used just like <strong><em>java</em></strong> and <strong><em>javah</em></strong>, except that it gives you a diagnostic output of what your class looks like (you'll need "-private" to get all of the methods, not just the public ones).  </p>
<p>If you give <strong><em>javap</em></strong> the "-s" option, it will also spit out the signature of each method, the one that you need for <strong><tt>RegisterNatives</tt></strong>.  It also happens to be the signature that you'll need to look up the method ID for calling a Java method from native code.  That makes it a little more valuable to learn, and after a while, you won't need <strong><em>javap</em></strong>.  I can write signatures just by looking at the Java method declaration (it gets a little trickier with generics, though).</li>
<li>
<h4>Adding a Java method won't have unexpected results:</h4>
<p>Because the mapping is explicit, and you wrote it, using <strong><tt>RegisterNatives</tt></strong> to map Java to native methods won't have any weird results when you add a new Java method.  The mapping remains valid.</li>
<li>
<h4>None of the native interface is exposed, except perhaps for a static "<strong><tt>init</tt></strong>" function:</h4>
<p>If you're concerned about the security of the native interface, the <strong><em>javah</em></strong> way of doing things will leave your native implementations exposed to the elements.  If you call <strong><tt>RegisterNatives</tt></strong> from your "<strong><tt>init</tt></strong>" static method, however, all the mapping can be done at runtime.  If this sounds like "security through obscurity," it is.  However, that's pretty much the best you get with Java (and native code, but often the obfuscation is easier).</p>
<p>One of the problems with <strong><em>javah</em></strong> that I forgot to mention (aside from exposing your entire interface, yielding confusing function names, and sometimes giving you unexpected results) is that the exported functions are fixed at runtime.  This may seem like an obvious requirement, but it isn't necessarily so if you use <strong><tt>RegisterNatives</tt></strong>.
</li>
</ul>
<p>Enough jabbering on about <strong><tt>RegisterNatives</tt></strong>.  How do you <em>use</em> it?</p>
<p>Like I said, it's pretty straightforward.  In your static native "<strong><tt>init</tt></strong>" function (I'm assuming that you set one of these up so that it's called in a static initializer), set up the map; let's use <strong><tt>NativeClass</tt></strong> from the last post, and signatures from <strong><em>javap</em></strong>: </p>
<p>[sourcecode language='cpp']JNIEXPORT void JNICALL Java_my_NativeClass_init<br />
  (JNIEnv *env, jclass cls)<br />
{<br />
  JNINativeMethod methods[] = {<br />
    // name, signature, function pointer<br />
    { "doStuff", "(Ljava/lang/String;II)V", &doStuff_string },<br />
    { "doStuff", "(F)V", &doStuff_float },<br />
    { "performAdmirably", "([ZLjava/lang/Runnable;DD)J", &performAdmirably_array },<br />
    { "performAdmirably", "(F)J", &performAdmirably_float }<br />
  };<br />
...[/sourcecode]</p>
<p>Notice that I keep the <strong><em>javah</em></strong> style for <strong><tt>init</tt></strong>.  That means that the JVM can find it right away when it loads the library.  Now call <strong><tt>RegisterNatives</tt></strong>:</p>
<p>[sourcecode language='cpp']...<br />
  env->RegisterNatives(cls, methods, 4);<br />
}[/sourcecode]</p>
<p>Pretty simple.  What to the implementations of the functions look like?  They're actually pretty close to what we saw from <strong><em>javah</em></strong>:</p>
<p>[sourcecode language='cpp']...<br />
/*<br />
 * Class:     my_NativeClass<br />
 * Method:    doStuff<br />
 * Signature: (Ljava/lang/String;II)V<br />
 */<br />
void JNICALL doStuff_string<br />
  (JNIEnv *, jobject, jstring, jint, jint)<br />
{}</p>
<p>/*<br />
 * Class:     my_NativeClass<br />
 * Method:    doStuff<br />
 * Signature: (F)V<br />
 */<br />
void JNICALL doStuff_float<br />
  (JNIEnv *, jobject, jfloat)<br />
{}</p>
<p>/*<br />
 * Class:     my_NativeClass<br />
 * Method:    performAdmirably<br />
 * Signature: ([ZLjava/lang/Runnable;DD)J<br />
 */<br />
jlong JNICALL performAdmirably_array<br />
  (JNIEnv *, jobject, jbooleanArray, jobject, jdouble, jdouble)<br />
{<br />
  return 0;<br />
}</p>
<p>/*<br />
 * Class:     my_NativeClass<br />
 * Method:    performAdmirably<br />
 * Signature: (F)J<br />
 */<br />
jlong JNICALL performAdmirably_float<br />
  (JNIEnv *, jobject, jfloat)<br />
{<br />
  return 0;<br />
}<br />
...[/sourcecode]</p>
<p>They have to have the same arguments, or else the JVM would crash calling them.  The nice thing is that you can give them names that make sense.  Also, it's not difficult to figure out what arguments should be there.  I recommend using <strong><em>javah</em></strong> for a while until you get used to seeing what should go into the declarations.</p>
<p>Notice that I drop <strong><tt>JNIEXPORT</tt></strong>, but retain <strong><tt>JNICALL</tt></strong>.  There's a reason for that; it's very important (at least on Windows; not so much on other platforms) to make sure that the calling convention matches what the JVM expects.  <strong><tt>JNICALL</tt></strong> is the way to do that.</p>
<p>Compile the native library, and run your class.  Assuming that you've called <strong><tt>init</tt></strong> from your static initializer after you call <strong><tt>System.loadLibrary</tt></strong>, you should be able to use all of your methods.</p>
<p>In the next post, I'll talk about some suggestions for how to declare your native methods.</p>
<p><a href="http://digg.com/submit?url=http%3A%2F%2Fcombativecoder.wordpress.com%2F2008%2F06%2F14%2Fgetting-a-class-started-with-jni-part-3-native-methods-using-registernatives&#38;title=Getting%20a%20Class%20Started%20with%20JNI%2C%20Part%203%3A%20Native%20Methods%20Using%20RegisterNatives&#38;topic=programming"><img src="http://digg.com/img/badges/100x20-digg-button.gif" width="100" height="20" alt="Digg!" style="border:none;" /></a> <a href="http://reddit.com/submit?url=http%3A%2F%2Fcombativecoder.wordpress.com%2F2008%2F06%2F14%2Fgetting-a-class-started-with-jni-part-3-native-methods-using-registernatives&#38;title=Getting%20a%20Class%20Started%20with%20JNI%2C%20Part%203%3A%20Native%20Methods%20Using%20RegisterNatives"><img src="http://s3.amazonaws.com/sp.reddit.com/reddit80x15b.gif" alt="Reddit This" style="border:none;" /></a></p>
<p>Footnotes:</p>
<p><a href="#bk1" name="fn1" title="Footnote 1">[1]</a> Well, you could, but you'd need to code one up yourself; maybe that's a project I'll take on for learning OCaml.</p>
<p>Tags: <a href="http://technorati.com/tag/JNI" rel="tag">JNI</a>, <a href="http://technorati.com/tag/Java" rel="tag">Java</a>, <a href="http://technorati.com/tag/DLL" rel="tag">DLL</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Getting a Class Started with JNI, Part 2: Native Methods Using javah]]></title>
<link>http://combativecoder.wordpress.com/?p=20</link>
<pubDate>Wed, 11 Jun 2008 04:39:41 +0000</pubDate>
<dc:creator>John Moeller</dc:creator>
<guid>http://combativecoder.wordpress.com/?p=20</guid>
<description><![CDATA[In the last post, I talked about how to set up your native library.  We didn&#8217;t really add any ]]></description>
<content:encoded><![CDATA[<p>In the <a href="2008/06/09/getting-a-class-started-with-jni-part-1-scaffolding/">last post</a>, I talked about how to set up your native library.  We didn't really add any implementations, though, and that's what I'll talk about in this post.</p>
<h4>Overview</h4>
<p>First, I think that it would probably be helpful to go over what a native method implementation looks like.  Say that we define a class called <strong><tt>my.NativeClass</tt></strong>, and we add the <strong><tt>init</tt></strong> static method to it like we did in the last post, and we add two methods, <strong><tt>doStuff</tt></strong> and <strong><tt>performAdmirably</tt></strong>:<br />
<!--more--><br />
[sourcecode language='java']public class NativeClass<br />
{<br />
  static {<br />
    System.loadLibrary("JNITest");<br />
    init();<br />
  }</p>
<p>  static native void init();</p>
<p>  public native void doStuff(String str, int x, int y);</p>
<p>  public native long performAdmirably<br />
    (boolean[] marks, Runnable r, double u, double v);</p>
<p>  public static void main(String[] args)<br />
  {<br />
    System.out.println("Entered main");<br />
  }<br />
}<br />
[/sourcecode]</p>
<p>We'll need to know what to put in the native file; Java code won't do.  I'm not going to worry right now about fleshing out these implementations.  As you can see, these are toy interfaces, and a tutorial about how to write a real native library deserves a more serious example.  Let's run <strong><em>javah</em></strong>.  A file named my_NativeClass.h is generated, with the following declarations:</p>
<p>[sourcecode language='C']...<br />
JNIEXPORT void JNICALL Java_my_NativeClass_init<br />
  (JNIEnv *, jclass);<br />
...<br />
JNIEXPORT void JNICALL Java_my_NativeClass_doStuff<br />
  (JNIEnv *, jobject, jstring, jint, jint);<br />
...<br />
JNIEXPORT jlong JNICALL Java_my_NativeClass_performAdmirably<br />
  (JNIEnv *, jobject, jbooleanArray, jobject, jdouble, jdouble);<br />
...[/sourcecode]</p>
<p>You'll notice that unlike <strong><tt>init</tt></strong>, <strong><tt>doStuff</tt></strong> and <strong><tt>performAdmirably</tt></strong> take as their second argument a variable of type <strong><tt>jobject</tt></strong>.  This reflects the fact that they are not static methods; they're instance methods.  The <strong><tt>jobject</tt></strong> parameter represents the instance that the method is being called on, and can be used to access fields and methods of the instance.  Likewise for static methods, the <strong><tt>jclass </tt></strong> parameter represents the class, and can be used in that capacity.</p>
<p>You've probably also noticed that the third parameter to the native <strong><tt>doStuff</tt></strong> is of type <strong><tt>jstring</tt></strong>.  Because <strong><tt>String</tt></strong>s are so often used in native code, and there are so many API functions in the JNI for them, it has its own type.  You'll notice the same thing about the third argument of <strong><tt>performAdmirably</tt></strong>; its type is <strong><tt>jbooleanArray</tt></strong> (all of the primitive array types have an equivalent native array type).  </p>
<p>The <strong><tt>Runnable</tt></strong> argument has no equivalent.  It's just a <strong><tt>jobject</tt></strong>.  All the primitive types have equivalents, and they actually carry the value of their respective variable; the other types represent Java references.  There are a couple more special types, but I'll get to them in a different post.</p>
<p>Copy the declarations to an implementation file, and leave the bodies blank (just return 0 from performAdmirably), and your Java class should run, assuming that you've done all the steps in the last post.</p>
<h4>Complicating things</h4>
<p>Ok, let's throw a wrench into things.  Create overloads for each of the functions we defined before.  Let's just give them each one float parameter:</p>
<p>[sourcecode language='java']public class NativeClass<br />
{<br />
  static {<br />
    System.loadLibrary("JNITest");<br />
    init();<br />
  }</p>
<p>  static native void init();</p>
<p>  public native void doStuff(String str, int x, int y);<br />
  public native void doStuff(float f);</p>
<p>  public native long performAdmirably<br />
    (boolean[] marks, Runnable r, double u, double v);<br />
  public native long performAdmirably(float f);</p>
<p>  public static void main(String[] args)<br />
  {<br />
    System.out.println("Entered main");<br />
  }<br />
}<br />
[/sourcecode]</p>
<p>If you re-run your Java class, things will probably still work.  If you try to call <em>both</em> versions of either function, however, you'll get an exception thrown.  This is because you don't have implementations for both overloads in your native library.  You probably expected this.</p>
<p>Here's the kicker, though: run <strong><em>javah</em></strong> again, recompile your native library, and try to run the java code again.  If you call both overloads, <em>neither</em> will work.  Open the header file, and you'll see why:</p>
<p>[sourcecode language='c']...<br />
JNIEXPORT void JNICALL Java_my_NativeClass_init<br />
  (JNIEnv *, jclass);<br />
...<br />
JNIEXPORT void JNICALL Java_my_NativeClass_doStuff__Ljava_lang_String_2II<br />
  (JNIEnv *, jobject, jstring, jint, jint);<br />
...<br />
JNIEXPORT void JNICALL Java_my_NativeClass_doStuff__F<br />
  (JNIEnv *, jobject, jfloat);<br />
...<br />
JNIEXPORT jlong JNICALL Java_my_NativeClass_performAdmirably___3ZLjava_lang_Runnable_2DD<br />
  (JNIEnv *, jobject, jbooleanArray, jobject, jdouble, jdouble);<br />
...<br />
JNIEXPORT jlong JNICALL Java_my_NativeClass_performAdmirably__F<br />
  (JNIEnv *, jobject, jfloat);<br />
...[/sourcecode]</p>
<p>The original declarations are gone, and have been replaced with declarations that are much more arcane.  This is the biggest problem that I have with <strong><em>javah</em></strong>.  Even if you add it to your build configuration so that it's run automatically, it may still cause unexpected linking issues at runtime if you change the Java interface.</p>
<p>In the end, though, this won't cripple your development.  If all that you're trying to do is stick a wrapper around a stable library, chances are high that you won't be maintaining the native interface very often.  If you're maintaining and updating your native library regularly, though, it can be inconvenient to keep examining the declarations generated by <strong><em>javah</em></strong> to make sure that you haven't missed anything.</p>
<h4>Summary</h4>
<p>To sum up, here's the pros and cons (as I see them) for <strong><em>javah</em></strong>:</p>
<h4>Pros:</h4>
<ol>
<li>Simple; you only have to run a command and the declarations are done</li>
<li>Great for whipping up a wrapper interface for a stable native library</li>
</ol>
<h4>Cons:</h4>
<ol>
<li>Not necessarily robust; changes in the Java interface can have unexpected results</li>
<li>Signature encoding for overloaded functions is odd and different from the encoding for the rest of the API (I'll explain this later, I promise)</li>
<li>It exposes the native interface to the world; I didn't mention this before, but if you're concerned about this kind of thing (especially if you're obfuscating your code), you may want to be careful about what native methods you expose, because they'll all show up in the library interface.</li>
</ol>
<p>Using <strong><em>javah</em></strong> is the <em>de rigeur</em> way of starting a native library.  In the next post, I'll talk about a different method, which works just as well, and is actually used by parts of the Java 2 API.</p>
<p>Tags: <a href="http://technorati.com/tag/JNI" rel="tag">JNI</a>, <a href="http://technorati.com/tag/Java" rel="tag">Java</a>, <a href="http://technorati.com/tag/DLL" rel="tag">DLL</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Getting a Class Started with JNI, Part 1: Scaffolding]]></title>
<link>http://combativecoder.wordpress.com/?p=17</link>
<pubDate>Mon, 09 Jun 2008 06:25:17 +0000</pubDate>
<dc:creator>John Moeller</dc:creator>
<guid>http://combativecoder.wordpress.com/?p=17</guid>
<description><![CDATA[In my posts on JNI_OnLoad and JNI_OnUnload, I talked about why and how you should use these function]]></description>
<content:encoded><![CDATA[<p>In my posts on JNI_OnLoad and JNI_OnUnload, I talked about why and how you should use these functions for a JNI library.  Now I'll talk about how to put together a Java class that uses native methods.</p>
<p>There are several reasons to use native functions; prominent among them are the ability to access special hardware and the ability to use pre-existing native libraries.</p>
<h4>Before you start:</h4>
<p><!--more--><br />
To get a class started with native code, here's the basic checklist that I use:</p>
<ol>
<li><strong>Set up your native code project or makefile:</strong> Make sure that you add the <strong><em>include</em></strong> directory from your JDK to the list of include directories, as well as <strong><em>include/{platform_name}</em></strong>.  The second one is important because otherwise, <strong><em>jni_md.h</em></strong> won't be found.  Unless you plan to fire up a JVM from your library, you won't need any special linker instructions, other than to specify that your library will be a shared library.</li>
<li><strong>Set up <strong><tt>JNI_OnLoad</tt></strong> and <strong><tt>JNI_OnUnload</tt></strong></strong>: I like to put these functions in a file of their own; many times I'll just use the default implementation file that my IDE generated for me.  These don't need a header file of their own; they're already declared in <strong><em>jni.h</em></strong> <a href="#fn1" name="bk1" title="Footnote 1">[1]</a>.  You can use the templates <a href="2008/06/04/using-jni_onload-and-jni_onunload-for-your-native-library-part-2/">found here</a>.</li>
<li><strong>Add code to the static initializer of your Java class:</strong>  There are things that you'll need to do to your Java class to get it to work with native code.  A call to <strong><tt>System.loadLibrary</tt></strong> is the most important part.  Without a call to this method, any call to a native method will throw <strong><tt>java.lang.UnsatisfiedLinkError</tt></strong>.  <strong><tt>System.loadLibrary</tt></strong> may also throw <strong><tt>java.lang.UnsatisfiedLinkError</tt></strong> if it can't find the library.  Be sure to make the library accessible to your Java class. <a href="#fn2" name="bk2" title="Footnote 2">[2]</a> It may also throw <strong><tt>java.lang.SecurityException</tt></strong> if the security manager doesn't like what the class is trying to do.
<p>The argument to <strong><tt>System.loadLibrary</tt></strong> doesn't need to have "lib" at the front or ".dll" at the end.  The call will add all the necessary decorations for your platform to the string that you give it.  Simply put:<br />
[sourcecode language='java']...<br />
  static {<br />
    System.loadLibrary("myNative");<br />
    ...<br />
  }<br />
...[/sourcecode]</li>
</ol>
<p>At this point, the class will load the native library and initialize it.  It can't do anything though, because we haven't implemented any native methods.  You might note that we don't <em>necessarily</em> need to call <strong><tt>System.loadLibrary</tt></strong> from the static initializer.  But it's going to make your life quite a bit easier if you do.  </p>
<p>You could load the native library with a singleton.  If you do this, though, you'll have to prod the singleton before every call to a native function.  The native library needs to be loaded and mapped before a native method call can be made.  If you make the necessary calls in the static initializer, no extra effort needs to be spent.  There are probably reasons to load the native library lazily, but for the most part, early initialization is fine.</p>
<h4>Adding native methods:</h4>
<p>At this point, we can start adding native methods.  Before you add any other native methods, I suggest that you add a <strong><tt>static native void</tt></strong> method named <strong><tt>init</tt></strong> (or some other name suitable to you) that takes no arguments, and call it in the static initializer, right after the call to <strong><tt>System.loadLibrary</tt></strong>:</p>
<p>[sourcecode language='java']...<br />
  static {<br />
    System.loadLibrary("myNative");<br />
    init();<br />
  }</p>
<p>  static native void init();<br />
...[/sourcecode]</p>
<p>The <strong><tt>init</tt></strong> native implementation will be a good place to cache all sorts of useful information and do all sorts of useful things.  I use something similar to it in all my classes that have native implementations.</p>
<p>If you try to run your Java code right now, it will throw <strong><tt>java.lang.UnsatisfiedLinkError</tt></strong>.  So we need to add a native implementation.  Before we do that, though, run <strong><em>javah</em></strong> on your Java class, the same way that you would invoke the class from the command line.  What you'll get is a C header file in the directory where you ran <strong><em>javah</em></strong> that declares the implementation of your native method:</p>
<p>[sourcecode language='c']/* DO NOT EDIT THIS FILE - it is machine generated */<br />
#include <jni.h><br />
/* Header for class testjni_TestJNI */</p>
<p>#ifndef _Included_testjni_TestJNI<br />
#define _Included_testjni_TestJNI<br />
#ifdef __cplusplus<br />
extern "C" {<br />
#endif<br />
/*<br />
 * Class:     testjni_TestJNI<br />
 * Method:    init<br />
 * Signature: ()V<br />
 */<br />
JNIEXPORT void JNICALL Java_testjni_TestJNI_init<br />
  (JNIEnv *, jclass);</p>
<p>#ifdef __cplusplus<br />
}<br />
#endif<br />
#endif[/sourcecode]</p>
<p>I ran <strong><em>javah</em></strong> on a class called <strong><tt>testjni.TestJNI</tt></strong> with the <strong><tt>init</tt></strong> method that I mentioned above.  As you can see, a function declaration called <strong><tt>Java_testjni_TestJNI_init</tt></strong> is generated.  If you add other functions to your Java class and repeat this process, they'll show up in the header file as well.  But I don't use them, for reasons that I'll cover in the next post.</p>
<p>For now, just cut the declaration from the header file and paste it into a new implementation file.  We don't need the header anymore:</p>
<p>[sourcecode language='cpp']#include <jni.h></p>
<p>extern "C" { </p>
<p>/*<br />
 * Class:     testjni_TestJNI<br />
 * Method:    init<br />
 * Signature: ()V<br />
 */<br />
JNIEXPORT void JNICALL Java_testjni_TestJNI_init<br />
(JNIEnv *, jclass)<br />
{}</p>
<p>}<br />
[/sourcecode]</p>
<p>Add this to your native project/makefile, build it, and test your Java class.  It should run just fine.</p>
<p>In the next post, I'll talk about how to write your native methods.</p>
<h4>Footnotes:</h4>
<p><a href="#bk1" name="fn1" title="Footnote 1">[1]</a> In fact, I don't usually set up header files for native functions.  The only entities that will be calling native method implementations are Java classes.  You probably won't run into any need to call them directly; you'll probably be calling some other functions that the native methods themselves call.  Therefore, there's no need to declare them in headers.<br />
<a href="#bk2" name="fn2" title="Footnote 2">[2]</a> There are a number of ways to do this; including setting the system property "java.library.path," and using the platform's way of locating shared libraries.</p>
<p>Tags: <a href="http://technorati.com/tag/JNI" rel="tag">JNI</a>, <a href="http://technorati.com/tag/Java" rel="tag">Java</a>, <a href="http://technorati.com/tag/DLL" rel="tag">DLL</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Using JNI_OnLoad and JNI_OnUnload for Your Native Library, Part 2]]></title>
<link>http://combativecoder.wordpress.com/?p=14</link>
<pubDate>Wed, 04 Jun 2008 05:35:58 +0000</pubDate>
<dc:creator>John Moeller</dc:creator>
<guid>http://combativecoder.wordpress.com/?p=14</guid>
<description><![CDATA[In Part 1, I talked about why you should use JNI_OnLoad for your native library.  In Part 2, I]]></description>
<content:encoded><![CDATA[<p>In <a href="http://combativecoder.wordpress.com/2008/06/02/using-jni_onload-and-jni_onunload-for-your-native-library-part-1/">Part 1</a>, I talked about <em>why</em> you should use <strong><tt>JNI_OnLoad</tt></strong> for your native library.  In Part 2, I'll talk about <em>how</em> you should use it.</p>
<p><!--more--></p>
<h4>Declarations</h4>
<p>Let's first look at the declarations for <strong><tt>JNI_OnLoad</tt></strong> and <strong><tt>JNI_OnUnload</tt></strong> from <strong><em>jni.h</em></strong>:</p>
<p>[sourcecode language='c']...<br />
/* Defined by native libraries. */<br />
JNIEXPORT jint JNICALL<br />
JNI_OnLoad(JavaVM *vm, void *reserved);</p>
<p>JNIEXPORT void JNICALL<br />
JNI_OnUnload(JavaVM *vm, void *reserved);<br />
...[/sourcecode]</p>
<p>You'll find this section way down at the end of the file.  <strong><tt>JNIEXPORT</tt></strong> and <strong><tt>JNICALL</tt></strong> are just macros defined to be platform-specific directives that determine how you get symbols exported from a native library.  They're defined for your platform in <strong><em>{platform name}/jni_md.h</em></strong>.</p>
<h4>Arguments</h4>
<p>You'll notice that <strong><tt>JNI_OnLoad</tt></strong> and <strong><tt>JNI_OnUnload</tt></strong> each have two arguments: <em><tt>vm</tt></em> and <em><tt>reserved</tt></em>.  Forget about <em><tt>reserved</tt></em>.  There's nothing super-secret or special that I know that you can do with it, and I haven't tried to find out because it's, well, <em>reserved</em>.  There may be a use for this variable on other JVMs than the Sun JVM.  If you try to do something undocumented or JVM-specific with this variable, you're asking for trouble in the future or on other platforms, respectively.</p>
<p>The <em><tt>vm</tt></em> argument is used to give you access to parts of the <em>Invocation API</em>, specifically the parts that you can use with an already-running JVM.  You can attach or detach the currently-running thread, get the currently-running thread if it's already attached, or destroy the JVM (if you're running a native library attached to a Java process, it would be silly to destroy the JVM; this is meant for native processes that start a JVM).</p>
<h4>What you should do</h4>
<p>There are lots of things that you <em>could</em> do in <strong><tt>JNI_OnLoad</tt></strong>.  You could even start your car with it (that isn't completely far-fetched; Java goes a lot of places).</p>
<p>But here's a few things that you <em>should</em> do:</p>
<ol>
<li>Return the JNI version that you want support for, and set it to at least <strong><tt>JNI_VERSION_1_4</tt></strong>.  Whether you use <strong><tt>JNI_VERSION_1_6</tt></strong> is between you and your comfort level with the latest versions of Java.</li>
<li>Store the <em><tt>vm</tt></em> argument.  The <em><tt>vm</tt></em> variable can be useful for a lot of things, and it will never change.  You can look it up again from the context of a mapped native function, but you can't from an arbitrary function without looking up the JVM first (which <em>requires</em> linking to the JVM library, which can complicate things).  If you have <em><tt>vm</tt></em>, why not just store it?  Stick it in a singleton or static variable.<br />
<br><br><br />
For example, say that a mapped native function sets up a callback to be run from some arbitrary native thread.  If the JVM is available to you, you save yourself a step.</li>
<li>Initialize anything else that you need library-wide and want to initialize early.  This includes library init routines, etc.  As I mentioned in Part 1, calling <strong><tt>DllMain</tt></strong> from statically-initialized code can be risky, so doing anything that might load a DLL should probably go in <strong><tt>JNI_OnLoad</tt></strong> instead (or be lazily initialized somewhere else).</li>
</ol>
<p>Is <strong><tt>JNI_OnLoad</tt></strong> a good place to store method IDs and class references?  Probably not.  The problem in doing this is that those objects only have a lifetime as long as their associated Java class, and the native library may live longer than that (it can link to multiple classes).  These objects should be refreshed when the class is loaded, so save such caching for a native method called from the static initializer of the class.  More on that in a different post.</p>
<h4><strong><tt>JNI_OnUnload</tt></strong></h4>
<p>You've probably noticed by now that I've neglected <strong><tt>JNI_OnUnload</tt></strong>.  This function gets called whenever the native library is released.  Note that this will be when the <em>class loader that stores it</em> is garbage-collected, so it isn't a good idea to assume that it will be called after any one particular class is collected.  In fact, it isn't a good idea to assume that it will be called <em>at all.</em>  If a native library is loaded by the default class loader, <a href="http://blogs.sun.com/alanbur/entry/jni_onunload_mostly_useless">that class loader may never get finalized</a>.  </p>
<p>In my opinion, the best that you can do in this function is to reset your previously-stored <em><tt>vm</tt></em> variable, to ensure that nothing else tries to use it (since the JVM has now officially divested itself of the library).  You should, of course, protect the variable against concurrent access.  Leave necessary library cleanup to a different function.</p>
<p>One thing to note here is that this illustrates a running theme in JNI programming.  It's easy to get something created, but it can be tedious to ensure its proper destruction.  It's one place where Java is very different from native code, and it comes out on JNI boundaries.</p>
<h4>Putting it together</h4>
<p>To sum up, here's a skeleton for <strong><tt>JNI_OnLoad</tt></strong> and <strong><tt>JNI_OnUnload</tt></strong> in C++:<br />
[sourcecode language='c++']// onload.cpp<br />
#include &#60;jni.h&#62;</p>
<p>#include &#60;vmutil.h&#62;<br />
#include &#60;otherlibrary.h&#62;</p>
<p>JNIEXPORT jint JNICALL<br />
JNI_OnLoad(JavaVM *vm, void *reserved)<br />
{<br />
    // Store the JVM<br />
    VM::getInstance().init(vm);</p>
<p>    // Do initialization here<br />
    OtherLibraryInit("Native", OTHER_LIBRARY_NO_ZUCCHINI);</p>
<p>    // Return the JNI version<br />
    return JNI_VERSION_1_4;<br />
}</p>
<p>JNIEXPORT void JNICALL<br />
JNI_OnUnload(JavaVM *vm, void *reserved)<br />
{<br />
    // Reset the JVM pointer<br />
    VM::getInstance().cleanup(vm);<br />
}<br />
[/sourcecode]</p>
<p>That concludes this post, and I'll talk about how to set up the Java class and native methods in a post to come soon.</p>
<p>Tags: <a href="http://technorati.com/tag/JNI" rel="tag">JNI</a>, <a href="http://technorati.com/tag/Java" rel="tag">Java</a>, <a href="http://technorati.com/tag/DLL" rel="tag">DLL</a></p>
<p>[Edited to use the <a href="http://faq.wordpress.com/2007/09/03/how-do-i-post-source-code/">source code widget</a>; that makes things a lot easier!]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Using JNI_OnLoad and JNI_OnUnload for Your Native Library, Part 1]]></title>
<link>http://combativecoder.wordpress.com/?p=11</link>
<pubDate>Mon, 02 Jun 2008 07:30:20 +0000</pubDate>
<dc:creator>John Moeller</dc:creator>
<guid>http://combativecoder.wordpress.com/?p=11</guid>
<description><![CDATA[When a Java class with native methods is loaded, it has no &#8220;wiring&#8221; to the native classe]]></description>
<content:encoded><![CDATA[<p>When a Java class with <strong><tt>native</tt></strong> methods is loaded, it has no "wiring" to the native classes until <strong><tt>System.loadLibrary("NativeLibName")</tt></strong> is called.  If it is exported by the library, <strong><tt>JNI_OnLoad</tt></strong> is called first.  After that, the JVM tries to map library symbols to native methods.</p>
<p><strong><tt>JNI_OnLoad</tt></strong> is there for two reasons: to specify the minimum JNI version needed by the library and to perform library initialization.  If it's not present in your library, the JVM will assume that it's only compliant with the minimum JNI version, 1.1.  </p>
<p>It may seem unnecessary to export <strong><tt>JNI_OnLoad</tt></strong> from your library if you don't have anything to initialize.  However, the minimum version of 1.1 isn't the best.  You should at least <!--more--> support 1.2.  Several good features were added in that version of the API.  If you want support for <strong><tt>java.nio.ByteBuffer</tt></strong>, you're going to need 1.4.  You probably won't need 1.6, unless you're really interested in the kind of reference you're looking at.  I have had no personal need for that level of introspection.  I'd recommend 1.4, unless you really need the features supplied in 1.6.</p>
<p>If you <em>do</em> have something that you want to do on library initialization, <strong><tt>JNI_OnLoad</tt></strong> is the best place to get it done.  If you're programming a DLL on Windows, then you may be tempted to do the initialization in <strong><tt>DllMain</tt></strong> instead.  I'd recommend against that for the following reasons:</p>
<ul>
<li>It's possible, though tedious, to perform lookups of information from the JVM within <strong><tt>DllMain</tt></strong>.  <strong><tt>JNI_OnLoad</tt></strong> gives you direct access to the JVM API functions.</li>
<li><strong><tt>JNI_OnLoad</tt></strong> isn't called from the context of <strong><tt>DllMain</tt></strong>.  That means that it's safe to load other DLLs from it, and also to look up Java classes.  A Java class may end up loading a native library of its own, which means that your program will deadlock if you try to do this lookup from <strong><tt>DllMain</tt></strong>.  <br><br>Oh yeah, if you didn't know, <strong><tt>DllMain</tt></strong> isn't reentrant, so you'll deadlock if you try to load a DLL in the context of <strong><tt>DllMain</tt></strong>.  That seems to be a fact that is overlooked in many forum posts on JNI, and it's one that will have you pulling out your hair if you don't know it or remember it.  <br><br>Static initialization also falls under that category, so be careful what you statically initialize in a native library DLL.  It's probably best to use a pointer for static data, and initialize the data in <strong><tt>JNI_OnLoad</tt></strong>.</li>
<li>Debugging in <strong><tt>DllMain</tt></strong> can get a bit wacky.  At least in Visual Studio, it can be difficult to set a breakpoint in <strong><tt>DllMain</tt></strong> and have it stop where you want it to.  With <strong><tt>JNI_OnLoad</tt></strong>, it's never a problem.</li>
</ul>
<p>I'll describe how to best utilize <strong><tt>JNI_OnLoad</tt></strong> in the second part of this post.</p>
<p>Tags: <a href="http://technorati.com/tag/JNI" rel="tag">JNI</a>, <a href="http://technorati.com/tag/Java" rel="tag">Java</a>, <a href="http://technorati.com/tag/DLL" rel="tag">DLL</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Intro to JNI]]></title>
<link>http://combativecoder.wordpress.com/?p=8</link>
<pubDate>Fri, 30 May 2008 08:42:37 +0000</pubDate>
<dc:creator>John Moeller</dc:creator>
<guid>http://combativecoder.wordpress.com/?p=8</guid>
<description><![CDATA[As I explained in my intro, I&#8217;ve used JNI quite a bit.  Here I&#8217;ll just go into a little ]]></description>
<content:encoded><![CDATA[<p>As I explained in <a href="http://combativecoder.wordpress.com/2008/05/30/introintro/">my intro</a>, I've used JNI quite a bit.  Here I'll just go into a little more detail on JNI.</p>
<h3>What is JNI?</h3>
<p>JNI stands for Java Native Interface.  It's simply a way for the JVM to interface with machine-native code.  JNI functions consist of implementations of Java methods that are declared <strong><tt>native</tt></strong>.  The code is provided in a shared library or DLL, and loaded by the Java program when a class needs it.</p>
<h3>Why would you use JNI?</h3>
<p>Despite breathless claims to the contrary, Java bytecode can't perform any faster than native code on any particular platform.  It may be the case that a particular implementation can run as fast or better on modern JVM's than a similar implementation in C or C++, but this isn't true generally (also, this comparison is prone to the apples-to-oranges problem).  There are good reasons to go all-Java, so I'm not trying to start the age-old Internet debate all over again.  Suffice it to say that there may be performance gains in using a native library.</p>
<p>Additionally, bytecode can't interact directly with hardware.  For example, if your program is written to take advantage of a GPU, it's likely that a native library will be involved somewhere in the picture.  JNI allows you to write code that takes advantage of these features available on your platform.</p>
<p>Another reason to use JNI is if you already have a working library that you want to take advantage of in Java code.  Say that you have some ancient library that works like a charm, and hasn't been altered in years, but no one wants to rewrite it in Java code, because it would be too much work.  This is a perfect application for JNI.  All that is necessary is to write a couple wrapper functions and make the calls to the legacy library.  (In theory, anyway; it usually gets a little more complex than that.)</p>
<h3>Books &#38; Links:</h3>
<p>If you're anything like me, you like a good text on the topic that you're interested in.  There are two books specifically for JNI in print:</p>
<ol>
<li> <a href="http://www.amazon.com/Java-Native-Interface-Programmers-Specification/dp/0201325772"><em>Java(TM) Native Interface: Programmer's Guide and Specification (The Java Series)</em></a> by Sheng Liang, Prentice Hall PTR (June 20, 1999)</li>
<li> <a href="http://www.amazon.com/Essential-Jni-Java-Native-Interface/dp/0136798950"><em>Essential Jni: Java Native Interface (Essential Java)</em></a> by Rob Gordon, Prentice Hall PTR (March 1998)</li>
</ol>
<p>The Liang book is considered to be the essential source on JNI programming.  In fact, it's free.  Don't pay for it.  <a href="http://java.sun.com/docs/books/jni/">It's available from Sun</a>.  I can't say anything about the Gordon book, because I haven't read it.  You'll notice that these books are almost nine years old and over ten years old, respectively.  That's because the JNI API has changed very little in that time.  A couple of API functions have been added, but for the most part, it's the same as it was in 1999, which can be kind of comforting.</p>
<p>I printed out a copy of the Liang book a while ago, and it served me well as a good starting point.  If you're in the need for JNI, and you want to get a good overview on how to use it, it's a good text.  When you start getting more complicated with it, though, that's when you need a little more info, and for the most part, it's not out there, except in scattered forum posts and Java bug descriptions.</p>
<p>An absolute must-bookmark link is this one: <a href="http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/jniTOC.html">the JNI Spec</a>.  If you do any JNI programming, you'll be referencing this page a lot.</p>
<h3>How do I use the JNI?</h3>
<p>One stumbling block for me and my colleagues was getting used to writing the JNI code.  I eventually came up with some rules of thumb for creating the JNI interface that sped up development time:</p>
<ol>
<li>Implement JNI_OnLoad and JNI_OnUnload for your native implementations; don't use DllMain on Windows</li>
<li>Don't run javah, use RegisterNatives() in your code</li>
<li>Use care in how you access arrays</li>
<li>Use peer objects, but make them loosely-coupled</li>
</ol>
<p>These are the points where I depart from Liang's book.  Most of what's in the book is sound advice, in my opinion.  Like it says, these are rules of thumb, not laws set in stone.  These are practices that worked well for me and my colleagues.  I will be getting to these each in separate posts.</p>
<h3>How do I debug JNI code?</h3>
<p>Another big difficulty lies in debugging native code that's called by Java code, or Java code that you're trying to use with native code, or both.  Getting everything to line up is tricky.  And it deserves a whole post.</p>
<p>Stay tuned for more on this topic, and I hope that you find it useful.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Intro]]></title>
<link>http://combativecoder.wordpress.com/?p=3</link>
<pubDate>Fri, 30 May 2008 05:59:18 +0000</pubDate>
<dc:creator>John Moeller</dc:creator>
<guid>http://combativecoder.wordpress.com/?p=3</guid>
<description><![CDATA[Welcome.  I started this blog because I thought that I had something to add to the dearth of softwar]]></description>
<content:encoded><![CDATA[<p>Welcome.  I started this blog because I thought that I had something to add to the dearth of software posts on the Internet.  I don't claim to be a general software expert; if I could, I'd write a book and make money from that kind of status (maybe someday, not now).</p>
<p>What I think that I <em>can</em> claim is some expertise in a few niche fields.  Note that I say "some expertise" instead of "that I am an expert."  Therefore, I'll usually try to state the source of my expertise if it isn't wholly my own.</p>
<p>The areas of expertise that I can claim here, and will most likely post on, are:</p>
<ol>
<li> <strong>JNI Programming:</strong> JNI stands for <em>Java Native Interface</em>, and is the standard way of extending Java with native code.  Much of the Java 2 API uses it (java.lang.Object has native methods), and its hooks have to be implemented by any compliant JVM.  The thing about JNI is that it *can* be incredibly tedious to use.  This subject deserves a post of its own, though, so I'll stop here.</li>
<li> <strong>Generic Programming:</strong> This is a method of programming in the same way that Object-Oriented Programming is a way of programming.  Generic programming goes off the idea that a function or class can be used with a wide variety of types, not just those that fit a certain interface.<br />
Generic programming can be taken further, and it can be used to build skeletons for basic design patterns that you can "fill in" with the classes of your choice.  There's a library provided by Adobe called the Generic Image Library that's built on this idea.  GP libraries use "concepts" instead of interface definitions to specify what a class should look like to be used with its generic constructs.<br />
I would say that I have an intermediate-level understanding of GP, so I feel that I could probably help those people trying to get started on it.</li>
<li><strong>Template Metaprogramming:</strong> Much like GP, this technique uses C++ templates, but it does so in a different way.  TMP uses templates to <em>generate</em> code, and can be used to "unroll" loops, control the selection of functions for overload, create functions, provide information on other constructs, plus many more uses (such as making GP work better).<br />
Again, I would say that I have an intermediate knowledge of this topic.</li>
<li><strong>The STL:</strong> I'm a big fan of the STL, and you should be too, if you use C++!  I'm definitely not an expert on the STL; I'd say intermediate here again, but it's really easy to gain a basic understanding of it, and a basic understanding will help out a ton, so I think that I can help out there.</li>
<li><strong>Parallel Programming:</strong> This is a big one, and there are heavier hitters out there, but I have a decent amount of experience with this topic, and it can be pretty important to get right.  I'll see if I can help.</li>
</ol>
<p>That about sums it up for stuff that I'm comfortable with; I do also know a fair amount about handling raw image data, but that's not quite as useful as the higher-level knowledge of manipulating images with transforms, so I'll probably leave that subject out.</p>
<p>As for other topics that I have an interest in, but am not well-versed in, I'll list those here briefly:</p>
<ul>
<li>GPU Programming</li>
<li>Functional languages (like OCaml or Haskell; no experience at all, in fact, but I want to teach myself, so I'll blog about that while it happens)</li>
<li>Image processing (like convolutions and transforms)</li>
</ul>
<p>I'll stop there.  Again, welcome, and I hope that you find this blog useful.</p>
<p>[Edit: trying to fix a couple formatting quirks]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Appeler du Java depuis .Net]]></title>
<link>http://grozeille.wordpress.com/?p=53</link>
<pubDate>Thu, 08 May 2008 18:34:15 +0000</pubDate>
<dc:creator>grozeille</dc:creator>
<guid>http://grozeille.wordpress.com/?p=53</guid>
<description><![CDATA[Deux mondes s&#8217;affrontent: Java et .Net. Chacun choisi son camp, ou choisi les deux&#8230; moi ]]></description>
<content:encoded><![CDATA[<p>Deux mondes s'affrontent: Java et .Net. Chacun choisi son camp, ou choisi les deux... moi j'ai la double nationalité :) Mais quand les deux mondes doivent alors communiquer? Je fais l'interprète. Voila le topo:<br />
J'ai une application .Net qui a besoin de manipuler des classes Java, et pour se faire je passe par <a href="http://en.wikipedia.org/wiki/C%2B%2B/CLI">C++/CLI</a>: comment avoir un pied dans du .Net et un autre dans du natif C++.<br />
<!--more--><br />
L'avantage de C++/CLI (<a href="http://en.wikipedia.org/wiki/Common_Language_Infrastructure">Common Language Infrastructure</a>) c'est qu'on peut mixer du code managé et non-managé. Je peux donc compiler un assembly .Net en C++, qui lui fait appelle à du pure code C++ natif. Ici en l'occurrence j'utilise <code>"jni.h"</code> pour communiquer avec la JVM à l'aide de <code>jvm.dll</code>.</p>
<p>Rentrons dans le vif du sujet: qu'est-ce que ça donne du coté de mon application C#:<br />
[code language='csharp']<br />
// on démarre la JVM avec mes bons arguments<br />
MathiasJniCpp.JVMWrapper.InitJvm(new String[] { "-Djava.class.path=Mathias.Jni.Java.jar" });</p>
<p>// on créer un objet .Net qui wrappe l'objet Java<br />
// en C++/CLI, le destructeur des classes CLI sert de méthode "Dispose"<br />
using (MathiasJniCpp.MyJavaWrapper javaObject = new MathiasJniCpp.MyJavaWrapper())<br />
{<br />
// faire mumuse avec...<br />
javaObject.People = "Mathias";<br />
Console.WriteLine(javaObject.SayHello());<br />
}</p>
<p>// on libère la JVM<br />
JVMWrapper.ReleaseJvm();<br />
[/code]</p>
<p><code>MathiasJniCpp</code> c'est le namespace de mon assembly c++/cli, j'en reparlerai plus tard.<br />
On voit que je manipule une classe JVMWrapper qui me permet de charger une JVM (et de la libérer). J'utilise aussi une classe .Net codé en C++/CLI. En fait, je l'utilise comme un classe C#, ou VB.net etc. C'est une classe "classique" .Net avec des méthodes et des propriétés.</p>
<p>Point intéressant à souligner: pourquoi utiliser <code>using</code>?<br />
Pour rappelle, il y a des mots-clefs en C# très lié au Framework (comme <code>foreach</code>) et <code>using</code> en fait partie. Il prend les objets qui implémente <code>IDisposable</code> et fait appelle à la méthode <code>Dispose()</code> à la fin du bloque. Comme ça, je suis sûr de libérer la classe du coté JVM quand j'en ai plus besoin.</p>
<p>Je ne vais pas montrer tout le code, car trop long et <a href="http://www.box.net/shared/ropzl4u80o">disponible ici</a>.<br />
Mais voici un aperçu de la classe C++:<br />
[code language='cpp']<br />
#include "jni.h"<br />
public ref class MyJavaWrapper<br />
{<br />
private:<br />
  static jmethodID initMethodId;<br />
  static jclass clazz;<br />
  jobject obj;<br />
public:<br />
  /* initialisation des métadata Java/JNI, à voir plus tard */<br />
  static void initJavaMetadata()<br />
  { ... }</p>
<p>  /* une méthode de notre classe Java que l'on wrappe, expliqué aussi plus tard */<br />
  String^ SayHello(String^ people)<br />
  { ... }</p>
<p>  /* constructeur */<br />
  MyJavaWrapper(void)<br />
  {<br />
    // histoire de récupérer toutes les métadatas nécessaires du coté Java<br />
    MyJavaWrapper::initJavaMetadata();</p>
<p>    // construction d'une instance avec le constructeur par défaut<br />
    this->obj = JVMWrapper::env->NewObject(MyJavaWrapper::clazz, MyJavaWrapper::initMethodId);<br />
  }</p>
<p>  /* "destructeur" */<br />
  virtual ~MyJavaWrapper(void)<br />
  {<br />
    JVMWrapper::env->DeleteLocalRef(this->obj);<br />
  }<br />
};<br />
[/code]<br />
<code>ref class</code> veut dire "c'est une classe .Net". Mais... ma classe n'implémente pas <code>IDisposable</code>!! Et c'est quoi ce destructeur??<br />
Et oui: le destructeur C++ pour un objet .Net est transformé en la méthode <code>Dispose()</code> et la classe devient alors forcement <code>IDisposable</code>. Pour gérer le <code>finalize</code> <a href="http://dotnet.developpez.com/faq/cppcli/?page=syntaxe#finalizer_vs_destructor">allez voir ici</a>.</p>
<p>Je manipule le membre <code>this-&#62;obj</code> qui est tout simplement un "pointeur" sur notre objet java. En fait, c'est un <code>jobject</code> qui est un type définie dans <code>"jni.h"</code>.<br />
J'utilise la classe JVMWrapper qui me permet de communiquer avec la JVM, et je lui demande de créer un nouvel objet d'une certaine classe <code>jclass</code> avec un certain constructeur <code>jmethodID</code> et j'obtiens ainsi mon <code>jobject</code>.<br />
<em>Étant donnée que la classe et la méthode ne change pas, j'ai rendu ces données <code>static</code>.</em></p>
<p>Voyons maintenant ce que fait <code>MyJavaWrapper::initJavaMetadata();</code>:<br />
[code language='cpp']<br />
/* initialise les metadata du coté Java */<br />
static void initJavaMetadata()<br />
{<br />
  // si les métadata ne sont pas déjà récupérées...<br />
  if(MyJavaWrapper::clazz == NULL)<br />
  {<br />
    MyJavaWrapper::clazz = JVMWrapper::env->FindClass("mathias/jni/java/MyJavaClass");<br />
    MyJavaWrapper::initMethodId = JVMWrapper::env->GetMethodID(MyJavaWrapper::clazz, "<init>", "()V");<br />
  }<br />
}<br />
[/code]</p>
<p>C'est la dedans que j'obtiens une fois pour toute la représentation de la classe Java <code>mathias.jni.java.MyJavaClass</code> et la représentation de la méthode <code>&#60;init&#62;</code> avec en paramètre <code>()V</code>.<br />
Pour comprend le lien avec la classe, il n'y a pas trop de problème: c'est le <a href="http://en.wikipedia.org/wiki/Fully_qualified_name">fully qualified name</a> avec des '/' au lieu des '.'.<br />
Mais en ce qui concerne la recherche d'une méthode, ça devient du charabia!!<br />
En fait, <code>&#60;init&#62;</code> est une méthode un peu spéciale: c'est un constructeur.<br />
Ensuite, on spécifie les arguments du constructeur que l'on cherche, et la on tombe sur une syntaxe barbare. Dans notre cas, on cherche le constructeur par défaut c'est à dire qui ne prend pas d'argument.<br />
Mais pour mieux comprendre la syntaxe barbare, voyons d'autres exemples de méthodes:<br />
[code language='cpp']<br />
JVMWrapper::env->GetMethodID(MyJavaWrapper::clazz, "setPeople", "(Ljava/lang/String;)V");<br />
[/code]<br />
Traduction: je cherche la méthode <code>setPeople</code> qui prend un argument de type <code>java.lang.String</code> et qui retourne <code>void</code>.<br />
Un autre exemple:<br />
[code language='cpp']<br />
JVMWrapper::env->GetMethodID(MyJavaWrapper::clazz, "sayHello", "([Ljava/lang/String;Z;)I");<br />
[/code]<br />
Traduction: je cherche la méthode <code>sayHello</code> qui prend un argument de type <code>java.lang.String[]</code> et un autre de type <code>boolean</code> et qui retourne un type <code>int</code>.</p>
<p>On retrouve cette syntaxe à beaucoup d'endroits, comme sous <a href="http://grozeille.files.wordpress.com/2008/05/eclipsejni.png">Eclipse</a> par exemple. Pour plus d'explication voir la <a href="http://java.sun.com/j2se/1.4.2/docs/guide/jni/spec/types.html">documentation officielle</a>.</p>
<p>Si l'on veut maintenant appeler une méthode Java, on récupère sa représentation tout comme on le fait avec le constructeur, puis on l'invoque sur notre instance:<br />
[code language='csharp']<br />
public ref class MyJavaWrapper<br />
{<br />
private:<br />
  static jmethodID initMethodId;<br />
  static jclass clazz;</p>
<p>  // notre représentation JNI de la méthode "sayHello"<br />
  static jmethodID sayHelloMethodId;</p>
<p>  jobject obj;<br />
public:<br />
  /* initialisation des métadata Java/JNI */<br />
  static void initJavaMetadata()<br />
  {<br />
    /* initialisation de la classe et du constructeur, comme vu précédemment<br />
    [...]  */</p>
<p>    // on récupère la représentation de "sayHello"<br />
    JVMWrapper::env->GetMethodID(MyJavaWrapper::clazz, "sayHello", "(Ljava/lang/String;)Ljava/lang/String");<br />
  }</p>
<p>  /* sur l'appelle de cette méthode .Net, on fait appelle à la méthode Java */<br />
  String^ SayHello(String^ people)<br />
  {<br />
    // j'utilise une classe spéciale pour convertir ma String^ .net en natif ou Java<br />
    StringConverter peopleStringConverter(people);<br />
    jstring jPeople = peopleStringConvert.toJava();</p>
<p>    // appelle de la méthode Java, j'ai le droit de caster en jstring car c'est un sous-type de jobject<br />
    jstring jResult = (jstring)JVMWrapper::env->CallObjectMethod(this->obj, sayHelloMethodId, jPeople);</p>
<p>    // conversion du type Java en .Net<br />
    StringConverter resultStringConvert(jResult);<br />
    return resultStringConvert.toDotnet();<br />
  }<br />
};<br />
[/code]</p>
<p>Voila, maintenant vous savez:</p>
<ul>
<li>obtenir la représentation d'une classe Java</li>
<li>obtenir la représentation d'une méthode d'une classe</li>
<li>créer une instance d'une classe Java</li>
<li>invoker des méthodes sur une instance</li>
</ul>
<p>En conclusion:<br />
l'API JNI c'est un peux comme utiliser la réflection. Ça a donc des conséquences en termes de performance. Pour information, créer 10000 objet en java prend <em>625ms</em>, en pure .net ça donne <em>46ms</em> et en .Net-&#62;JNI-&#62;Java ça donne <em>2.687s</em>.<br />
L'API JNI peut sembler barbare au début, mais on s'y fait :) et puis il y a <a href="http://java.sun.com/j2se/1.4.2/docs/guide/jni/spec/functions.html#wp20949">la doc</a>, alors <a href="http://en.wikipedia.org/wiki/RTFM">RTFM</a> ;).</p>
<p>C++/CLI c'est de la bombe en termes d'interop. C'est le pont parfait entre le monde .Net et le natif.<br />
L'inconvénient c'est que la syntaxe C++ est lourde. Et elle l'est d'autant plus en C++/CLI car il faut y ajouter les spécificités .Net, et il faut aussi distinguer une instance managée et non-managée, et tout ça passe par de nouveau symboles/mots-clefs.<br />
Les conversions de types entre les deux mondes ne sont pas faites implicitement, et il faut souvent jongler pour avoir le bon type. J'ai par exemple eu des problèmes lors des conversions de String avec JNI: il faut convertir la <code>String^</code> .net en <code>char*</code> natif pour enfin construire une <code>jstring</code>. Les conversions ont été le plus pénible dans l'histoire.</p>
<p>Enfin, voici le projet complet: <a href="http://www.box.net/shared/ropzl4u80o">Mathias.Jni.CSharp.zip</a><br />
Un petit rappel des liens utiles:</p>
<ul>
<li><a href="http://dotnet.developpez.com/faq/cppcli/">http://dotnet.developpez.com/faq/cppcli/</a></li>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/guide/jni/spec/jniTOC.html">http://java.sun.com/j2se/1.4.2/docs/guide/jni/spec/jniTOC.html</a></li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Does Android dream of something more than Java?]]></title>
<link>http://mantrid.wordpress.com/?p=53</link>
<pubDate>Mon, 28 Apr 2008 08:53:39 +0000</pubDate>
<dc:creator>mantrid</dc:creator>
<guid>http://mantrid.wordpress.com/?p=53</guid>
<description><![CDATA[Every time a new open technology appears, independent developers attempt to integrate it with other ]]></description>
<content:encoded><![CDATA[<p>Every time a new open technology appears, independent developers attempt to integrate it with other technologies. Programmers are often eager to try new stuff out especially in areas where it was not designed to be used. There's a lot of <em>porting </em>in all directions going on. By satisfying their curiosity they give everyone incredible innovations as a side effect. </p>
<p>When <a href="http://code.google.com/appengine/">Google App Engine</a> was released, there were immediately demands raised for support of other programming languages than Python. Developers wanted everything from Java and C# to Ruby and Scala.</p>
<p>Android is less than 6 months old, and just two weeks ago the great Android Developer Challenge was closed with more than 1700 submissions. Google achieved enormous interest in Android within the Java community. Not surprisingly, people started thinking about using other languages to develop apps on Android. </p>
<h3>C/C++</h3>
<p>Linux development in general is of course based on C and C++. Everything from kernel and its modules to windowed environments like GNOME and KDE to office applications is in most cases written in C/C++. The mobile world has also chosen C++ since it can provide best performance and memory usage what is so crucial in embedded environments. And since Android is in fact another Linux distro, an attempt of running native apps seems quite natural.</p>
<p>Aaron P. D’Souza <a href="http://groups.google.com/group/android-developers/browse_thread/thread/b0b59c09198139de">described how to compile and run</a> a tiny console program within emulator. Aaron used <a href="http://www.gnuarm.com/">GNU/ARM Linux toolchain</a> that can be <a href="http://www.codesourcery.com/gnu_toolchains/arm/download.html">downloaded here</a>. Also <a href="http://benno.id.au/blog/2007/11/13/android-native-apps">Benno came up with similar solution</a>.</p>
<p>Unfortunately, such native apps can't access all the cool features that make Android so special, since they are accessible only through Java framework. If you want mix C++ and Java but still send SMS messages, capture video or use location based services, you may however try to use JNI. Davanum Srinivas <a href="http://davanum.wordpress.com/2007/12/09/android-invoke-jni-based-methods-bridging-cc-and-java/">presents how to achieve this step by step</a>. This way one can make part of his app partially native to gain performance, for instance in case he uses some unique audio/video coding algorithms or advanced math, and call it from Java through JNI.</p>
<p>There is however a lot of doubt about these attempts. Even <a href="http://groups.google.com/group/android-developers/browse_thread/thread/278ac1b47594c37a">a discussion arose</a> on Google Groups. One of main concerns is such native code has to be compiled for every device out there that is going to run Android to make it fully supported. And Android was created to eliminate the need to recompile stuff. Hatem Ben Yacoub of Open Handset Magazine has <a href="http://openhandsetmagazine.com/2007/11/running-c-native-applications-on-android-the-final-point/">addressed the issue here</a>.</p>
<h3>Python, Jython</h3>
<p>There are some python scripts like <em>activityCreator.py </em>included within Android SDK. Moreover, we all know Python, along with Java, to be one of the most used languages by Google engineers. So, is it possible to write Python apps for Android?</p>
<p>First attempts of installing and running python snippets took <a href="http://groups.google.com/group/android-developers/msg/2f57efd7330ee641">Marcelo Barros de Almeida but he couldn't get it running</a>. There is of course a problem that, just like native apps, such scripts couldn't use all the features without creating special bindings to Android API first.</p>
<p>Jython might be of help here, allowing to run Python scripts within JVM (or rather Dalvik VM) and transparently access API. hdante tried to <a href="http://www.nabble.com/Android:-Jython-port--td14506402.html">use Jython on Android but it also appeared difficult</a>.</p>
<p>Google used Apache Harmony project that reimplements all Java standard APIs. Unfortunately, Harmony hasn't complete implementation of Java reflection and there are <em>java.beans.IntrospectionException thrown</em>. </p>
<h3>Ruby, JRuby and Groovy</h3>
<p>The <a href="http://www.ruby-forum.com/topic/130529">very same problem appears</a> in repect to Ruby and JRuby. Also <a href="http://jameswilliams.be/blog/entry/38">James Williams tried to bring Groovy to Android</a> with no success. <a href="http://www.nabble.com/Anyone-got-the-groovy-running-on-Android--td15044776.html">Here is some discussion</a>.</p>
<h3>Scala</h3>
<p>It seems the only team to get a "foreign" language run on Android are the Scala guys. They even <a href="http://www.nabble.com/-scala--Scala-on-Android-td14336400.html">made a dedicated Android Target</a> for their technology. There is a short description on <a href="http://www.scala-lang.org/downloads/targets/android.html">how to get a Scala snippet running in the emulator</a>.</p>
<h3>Other BIG players</h3>
<p>Sun must be quite worried Google thrown away their J2ME and made their own solution (Dalvik). Just as Sun tries a lot to get J2ME running on iPhone, we could wonder if they are going to try introducing JavaFX Mobile to Android in the future. Is Adobe going to make sure Flash runs in Android?</p>
<p>.NET and Mono communities are <a href="http://groups.google.com/group/android-developers/browse_thread/thread/68c24e29816c8bdb">considering workarounds</a> to allow running their code on Google's OS. Here are <a href="http://tirania.org/blog/archive/2007/Nov-13-1.html">some ideas by now</a>.</p>
<h3>Google Gears and JavaScript</h3>
<p><a href="http://gears.google.com/">Google Gears</a> brings the opportunity to develop desktop-like applications in JavaScript. Combined with <a href="http://code.google.com/webtoolkit/">GWT</a> and run within Android's WebKit browser, it could grow in time to become another app platform. And since all modern handheld devices are equipped with AJAX-capable browsers, Gears+GWT tandem could let us create applications that run on more than Android: including iPhone, Windows Mobile and Symbian-based phones. There are successful attempts in <a href="http://timepedia.blogspot.com/2007/11/gwt-and-android-marriage-made-in-heaven.html">bringing GWT to Android</a>. Gears in mobile world is currently ported to Windows Mobile only but we can be pretty sure we shall see it in WebKit based browsers too. There are rumors that porting Gears to Safari has been already started.</p>
<p>Gears open up possibilities to use Dojo, JQuery, YUI, GWT and many more. It would also allow us to reuse code of our existing AJAX-enabled web apps straight into mobile version, thus reducing significantly its implementation time.</p>
<h3>What about J2ME?</h3>
<p>A frequent question that appears on various forums is how to run J2ME applications on Android. Since Android itself does not support Java ME, there are attempts to fill the gap. <a href="http://kobjects.sourceforge.net/me4se/">ME4SE</a> is a project that aims to supplement SE with ME so J2ME software could be run in J2SE environment. Poliplus created <a href="http://devphone.com/me4android-java-me-on-top-of-android">ME4android</a> that allows to <a href="http://www.poliplus.com/android.htm">port your J2ME application to Android</a>.</p>
<h3>Conclusion</h3>
<p>Android uses Dalvik VM instead of JVM. Dalvik bytecode is incompatible with Java bytecode. It makes impossible to implement dynamic Class Loaders known in web development. For instance <a href="http://code.google.com/p/i-jetty/">iJetty </a>(<a href="http://www.mortbay.org/jetty-6/">Jetty </a>port to Android) cannot load <em>.war</em>-packaged web apps on the fly. Apache Harmony isn't complete yet and since Android uses it, there are some significant problems so far. This all makes quite hard to port other languages and technologies to Android, though it is widely described to be noting but Linux and Java. This issues are said to be fixed soon but by that time any attempts to use other languages on Android may be impossible to succeed. It seems we are bound to Java for some time, we can give Scala a try or even start thinking about Gears. Gears could be in future the real "write-once-run-everywhere" solution, assuming of course that this "dream" is possible after all.</p>
<p>Some of the links I posted here are months old, so things might have changed by now. If anyone succeeded in porting other languages to Android, please let us know in comments.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[HELLO WORLD JNI DI LINUX]]></title>
<link>http://dwibasuki.wordpress.com/?p=8</link>
<pubDate>Thu, 17 Apr 2008 11:39:49 +0000</pubDate>
<dc:creator>ag2uki</dc:creator>
<guid>http://dwibasuki.wordpress.com/?p=8</guid>
<description><![CDATA[Saya yakin, yang kesulitan menggunakan JNI bukanlah saya seorang. JNI teh naon nya? Bagi anda yang b]]></description>
<content:encoded><![CDATA[<p>Saya yakin, yang kesulitan menggunakan JNI bukanlah saya seorang. JNI teh naon nya? Bagi anda yang belum tahu teori apa itu JNI, silakan browsing-browsing dulu. Bila anda sudah tahu teorinya, dan udah gak sabar pengen nyoba di linux, semoga tulisan ini bisa jadi panduan. :D</p>
<p>Oke, sebelum mulai, pastikan sesajen berikut ini sudah terinstall di linux anda:<br />
1. JDK, untuk compile kode java anda<br />
2. gcc, beserta libc6 untuk compile kode C anda<br />
3. Eclipse (optional), sebagai editor<br />
Yak, cukup itu sajen yang diperlukan dalam ritual ini. Sebagain informasi saja, sajen yang terakhir sifatnya sunah. Anda boleh menggunakan editor lainnya.</p>
<p>Untuk mulai mencoba JNI, buat dulu source java anda sebagai berikut (file: NevNat.java):</p>
<p><code>package com.uki.coba;</code></p>
<p>public class NevNat {<br />
static {<br />
System.loadLibrary("nevnative");<br />
}<br />
public native void display() ;</p>
<p>public static void main(String[] args) {<br />
NevNat nat = new NevNat();<br />
nat.display();<br />
}</p>
<p>}</p>
<p>Setelah jadi, simpan dan compile source java tersebut.</p>
<p><code>gue@linux:~$ javac com/uki/coba/NevNat.java</code></p>
<p>Hasil komipilasi file tersebut menghasilkan file NevNat.class. Abis itu, dari file NevNat.class dibikin file C headernya, caranya:</p>
<p><code>gue@linux:~$ javah com.uki.coba.NevNat</code></p>
<p>Hasilnya adalah file com_uki_coba_NevNat.h. Isinya:</p>
<p><code>/* DO NOT EDIT THIS FILE - it is machine generated */<br />
#include &#60;jni.h&#62;<br />
/* Header for class com_uki_coba_NevNat */</code></p>
<p>#ifndef _Included_com_uki_coba_NevNat<br />
#define _Included_com_uki_coba_NevNat<br />
#ifdef __cplusplus<br />
extern "C" {<br />
#endif<br />
/*<br />
* Class:     com_uki_coba_NevNat<br />
* Method:    display<br />
* Signature: ()V<br />
*/<br />
JNIEXPORT void JNICALL Java_com_uki_coba_NevNat_display<br />
(JNIEnv *, jobject);</p>
<p>#ifdef __cplusplus<br />
}<br />
#endif<br />
#endif</p>
<p>Nah, langkah selanjutnya adalah membuat source C yang mengimplementasi header tersebut.<br />
Isinya sebagai berikut:<br />
<code>#include &#60;jni.h&#62;<br />
#include "com_uki_coba_NevNat.h"<br />
#include &#60;stdio.h&#62;</code></p>
<p>JNIEXPORT void JNICALL Java_com_uki_coba_NevNat_display<br />
(JNIEnv *env, jobject obj) {<br />
printf("Hello dab!\n");<br />
return;<br />
}</p>
<p>Kalo udah dibuat, tinggal compile</p>
<p><code>gcc -shared -I $JAVA_HOME/include/ -I $JAVA_HOME/include/linux/  NevNatImpl.c -o libnevnative.so<br />
</code></p>
<p>Trus, kalo udah kelas java tadi dijalankan aja</p>
<p><code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.<br />
gue@linux:~$ java com/uki/coba/NevNat<br />
</code></p>
<p>Hasilnya:<br />
<code>Hello dab!<br />
</code></p>
<p>http://www.devarticles.com/c/a/Java/Interacting-With-C-From-Java-With-JNI-Part-1/1/</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Accessing Windows Native API using Java]]></title>
<link>http://technicalmumbojumbo.wordpress.com/?p=25</link>
<pubDate>Thu, 20 Mar 2008 06:24:10 +0000</pubDate>
<dc:creator>Mr. President</dc:creator>
<guid>http://technicalmumbojumbo.wordpress.com/?p=25</guid>
<description><![CDATA[I was looking at alternatives besides JNI(Java Native Interface) to accessing Windows native API.
I ]]></description>
<content:encoded><![CDATA[<p>I was looking at alternatives besides JNI(Java Native Interface) to accessing Windows native API.<!--more--></p>
<p>I came across two open source projects <a title="Java Native Access" href="https://jna.dev.java.net/" target="_blank">Java Native Access</a>( will be referred to as JNA) and <a title="JNative" href="http://jnative.free.fr/" target="_blank">JNative</a>. I initially started with JNA and also came across a useful <a title="JNA Tutorial" href="http://www.javaworld.com/cgi-bin/mailto/x_java.cgi" target="_blank">tutorial</a> for the same. Unfortunately I tried developing access to other Windows API and came across issues such as procedure not found. I was unable to find a suitable way for mapping the native data types like LPTSTR or LPDWORD.</p>
<p>After spending some frustrating hours I gave up and started with JNative. Using JNative is a breeze especially since<br />
the project provides sample implementations for standard Windows DLLs like kernel32, GDI32, User32, Advapi32 etc.<br />
These implemenation classes act as references for custom implementations. All in all I am for JNative project for abstracting Java Native access.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JNI - Java Native Interface]]></title>
<link>http://wmagician.wordpress.com/2007/12/30/jni-java-native-interface/</link>
<pubDate>Sun, 30 Dec 2007 02:21:51 +0000</pubDate>
<dc:creator>wmagician</dc:creator>
<guid>http://wmagician.wordpress.com/2007/12/30/jni-java-native-interface/</guid>
<description><![CDATA[Java Native Interface (JNI) é um framework de programação que permite o código executado pela Ja]]></description>
<content:encoded><![CDATA[<p>Java Native Interface (JNI) é um framework de programação que permite o código executado pela Java Virtual Machine chamar e ser chamado por aplicações nativas (aplicações específicas para um hardware e sistema operativo) e por bibliotecas escritas em outras linguagens, tais como C, C++, Delphi e Assembly.</p>
<p>Como todos os frameworks JNI também tem as suas implicações, o uso do JNI coloca em risco dois benefícios da plataforma Java. Primeiro as aplicações Java que utilizam JNI ficam dependentes do ambiente de execução, contrário de Java puro que pode ser executado em múltiplos ambientes com JNI a parte nativa tem de ser recompilada em cada um dos ambientes de execução, perdendo a portabilidade do Java. Segundo a linguagem de programação Java é uma linguagem type-safe e  segura, ao contrario das linguagens nativas como C ou C++ que não são seguras.</p>
<p>Por estas razões o uso de JNI deve ser feito de forma cuidada e apenas caso não seja possível implementar apenas com a linguagem Java.<br />
Depois desta breve introdução vamos passar então à prática, vamos ver quais os passos necessários para a criação de um programa em Java com JNI.<br />
<img src="http://img230.imageshack.us/img230/4971/jniip5.gif" align="left" height="753" width="502" /></p>
<p>Depois de vermos o percurso a percorrer vamos começar com a implementação da classe HelloWorld.java</p>
<pre><span style="color:#cc66cc;">1</span> <span style="color:#000000;font-weight:bold;">public</span> <span style="color:#000000;font-weight:bold;">class</span> HelloWorld<span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">2</span>
<span style="color:#cc66cc;">3</span>	<span style="color:#000000;font-weight:bold;">private</span> <span style="color:#000000;font-weight:bold;">native</span> <span style="color:#993333;">void</span> print<span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">4</span>
<span style="color:#cc66cc;">5</span>	<span style="color:#000000;font-weight:bold;">public</span> <span style="color:#000000;font-weight:bold;">static</span> <span style="color:#993333;">void</span> main<span style="color:#66cc66;">(</span><a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AString+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">String</span></a> args<span style="color:#66cc66;">[</span><span style="color:#66cc66;">]</span><span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">6</span>      		<span style="color:#000000;font-weight:bold;">new</span> HelloWorld<span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>.<span style="color:#006600;">print</span><span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">7</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">8</span>
<span style="color:#cc66cc;">9</span>	<span style="color:#000000;font-weight:bold;">static</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">10</span>     		<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3ASystem+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">System</span></a>.<span style="color:#006600;">loadLibrary</span><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"HelloWorld"</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">11</span> 	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">12</span> <span style="color:#66cc66;">}</span></pre>
<p>Na linha 3 foi declarado o método nativo print e nas linhas 9 e 10 é dito ao Java para carregar o biblioteca “HelloWorld”, que vamos criar depois de realizar mais alguns passos. Em seguida vamos compilar a classe criada : javac HelloWorld.java.<br />
Depois de obtermos o ficheiro HelloWorld.class vamos usar a ferramenta javah do Java para criar o ficheiros header (HelloWorld.h), com o comando javah -jni HelloWorld vamos obter o ficheiro HelloWorld.h com o seguinte conteúdo.</p>
<pre><span style="color:#cc66cc;">1</span> <span style="color:#808080;font-style:italic;">/* DO NOT EDIT THIS FILE - it is machine generated */</span>
<span style="color:#cc66cc;">2</span>	<span style="color:#339933;">#include &#60;jni.h&#62;</span>
<span style="color:#cc66cc;">3</span>	<span style="color:#808080;font-style:italic;">/* Header for class HelloWorld */</span>
<span style="color:#cc66cc;">4</span>
<span style="color:#cc66cc;">5</span>	<span style="color:#339933;">#ifndef _Included_HelloWorld</span>
<span style="color:#cc66cc;">6</span>	<span style="color:#339933;">#define _Included_HelloWorld</span>
<span style="color:#cc66cc;">7</span>	<span style="color:#339933;">#ifdef __cplusplus</span>
<span style="color:#cc66cc;">8</span>	<span style="color:#000000;font-weight:bold;">extern</span> <span style="color:#ff0000;">"C"</span> <span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">9</span>	<span style="color:#339933;">#endif</span>
<span style="color:#cc66cc;">10</span>	<span style="color:#808080;font-style:italic;">/*
11	* Class:     HelloWorld
12 	* Method:    print
13 	* Signature: ()V
14 	*/</span>
<span style="color:#cc66cc;">15</span>	JNIEXPORT <span style="color:#993333;">void</span> JNICALL Java_HelloWorld_print <span style="color:#66cc66;">(</span>JNIEnv *, jobject<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">16</span>
<span style="color:#cc66cc;">17</span>	<span style="color:#339933;">#ifdef __cplusplus</span>
<span style="color:#cc66cc;">18</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">19</span>	<span style="color:#339933;">#endif</span>
<span style="color:#cc66cc;">20</span>	<span style="color:#339933;">#endif</span></pre>
<p>Como podemos ver na linha 15 é declarado o header para o método nativo que iremos implementar, vamos usar essa header para criar o ficheiro de código nativo (HelloWorld.c), como podemos ver em seguida.</p>
<p>Na linha 3 foi declarado o método nativo print e nas linhas 9 e 10 é dito ao Java para carregar o biblioteca “HelloWorld”, que vamos criar depois de realizar mais alguns passos. Em seguida vamos compilar a classe criada : javac HelloWorld.java.<br />
Depois de obtermos o ficheiro HelloWorld.class vamos usar a ferramenta javah do Java para criar o ficheiros header (HelloWorld.h), com o comando javah -jni HelloWorld vamos obter o ficheiro HelloWorld.h com o seguinte conteúdo.</p>
<pre><span style="color:#cc66cc;">1</span> <span style="color:#808080;font-style:italic;">/* DO NOT EDIT THIS FILE - it is machine generated */</span>
<span style="color:#cc66cc;">2</span>	<span style="color:#339933;">#include &#60;jni.h&#62;</span>
<span style="color:#cc66cc;">3</span>	<span style="color:#808080;font-style:italic;">/* Header for class HelloWorld */</span>
<span style="color:#cc66cc;">4</span>
<span style="color:#cc66cc;">5</span>	<span style="color:#339933;">#ifndef _Included_HelloWorld</span>
<span style="color:#cc66cc;">6</span>	<span style="color:#339933;">#define _Included_HelloWorld</span>
<span style="color:#cc66cc;">7</span>	<span style="color:#339933;">#ifdef __cplusplus</span>
<span style="color:#cc66cc;">8</span>	<span style="color:#000000;font-weight:bold;">extern</span> <span style="color:#ff0000;">"C"</span> <span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">9</span>	<span style="color:#339933;">#endif</span>
<span style="color:#cc66cc;">10</span>	<span style="color:#808080;font-style:italic;">/*
11	* Class:     HelloWorld
12 	* Method:    print
13 	* Signature: ()V
14 	*/</span>
<span style="color:#cc66cc;">15</span>	JNIEXPORT <span style="color:#993333;">void</span> JNICALL Java_HelloWorld_print <span style="color:#66cc66;">(</span>JNIEnv *, jobject<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">16</span>
<span style="color:#cc66cc;">17</span>	<span style="color:#339933;">#ifdef __cplusplus</span>
<span style="color:#cc66cc;">18</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">19</span>	<span style="color:#339933;">#endif</span>
<span style="color:#cc66cc;">20</span>	<span style="color:#339933;">#endif</span></pre>
<p>Como podemos ver na linha 15 é declarado o header para o método nativo que iremos implementar, vamos usar essa header para criar o ficheiro de código nativo (HelloWorld.c), como podemos ver em seguida.</p>
<pre><span style="color:#cc66cc;">1</span> include &#60;jni.<span style="color:#202020;">h</span>&#62;
<span style="color:#cc66cc;">2</span>	<span style="color:#339933;">#include &#60;stdio.h&#62;</span>
<span style="color:#cc66cc;">3</span>	<span style="color:#339933;">#include "HelloWorld.h"</span>
<span style="color:#cc66cc;">4</span>
<span style="color:#cc66cc;">5</span>	JNIEXPORT <span style="color:#993333;">void</span> JNICALL Java_HelloWorld_print<span style="color:#66cc66;">(</span>JNIEnv *env, jobject obj<span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">6</span>        		<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color:#000066;">printf</span></a><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"Hello World!<span style="color:#000099;font-weight:bold;">\n</span>"</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">7</span>        		<span style="color:#b1b100;">return</span>;
<span style="color:#cc66cc;">8</span>	<span style="color:#66cc66;">}</span></pre>
<p>Se observar-mos vamos ver que a linha 15 do ficheiro HelloWorld.h é praticamente igual ao código na linha 5 do ficheiro HelloWorld.c.<br />
Agora que já dispomos de todos os ficheiros necessários “HelloWorld.java”, “HelloWorld.class”, “HelloWorld.h” e “HelloWorld.c” vamos criar a nossa biblioteca nativa. Vamos ver como o fazer em diferentes sistemas operativos.</p>
<p>Linux com GCC</p>
<div class="code">
<pre style="margin-top:0;display:inline;">gcc -fPIC -I jdk/include -I jdk/include/linux -shared -o libHelloNative.so HelloNative.c</pre>
</div>
<p>Solaris com Sun Compiler</p>
<div class="code">
<pre style="margin-top:0;display:inline;">cc -G -I jdk/include -I jdk/include/solaris -o libHelloNative.so HelloNative.c</pre>
</div>
<p>Windows com MS C++ Compiler</p>
<div class="code">
<pre style="margin-top:0;display:inline;">cl -I jdk\include -I jdk\include\win32 -LD HelloNative.c -FeHelloNative.dll</pre>
</div>
<p>Onde jdk é o caminho para a pasta de instalação do Java.</p>
<p>Vamos agora ver como realizar a passagem de dados entre Java e C através do JNI. Para isso criamos um pequeno programa em que vamos imprimir uma pergunta, usar a função scanf do C para recolher o input e retorná-lo para o Java como um Objecto String. Para isso vamos começar claro pela criação do ficheiro Prompt.java.</p>
<pre><span style="color:#cc66cc;">1</span> <span style="color:#000000;font-weight:bold;">public</span> <span style="color:#000000;font-weight:bold;">class</span> Prompt<span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">2</span>	<span style="color:#000000;font-weight:bold;">private</span> <span style="color:#000000;font-weight:bold;">native</span> <a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AString+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">String</span></a> getLine<span style="color:#66cc66;">(</span><a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AString+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">String</span></a> prompt<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">3</span>
<span style="color:#cc66cc;">4</span>	<span style="color:#000000;font-weight:bold;">public</span> <span style="color:#000000;font-weight:bold;">static</span> <span style="color:#993333;">void</span> main<span style="color:#66cc66;">(</span><a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AString+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">String</span></a> args<span style="color:#66cc66;">[</span><span style="color:#66cc66;">]</span><span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">5</span>		Prompt p = <span style="color:#000000;font-weight:bold;">new</span> Prompt<span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">6</span>		<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AString+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">String</span></a> input = p.<span style="color:#006600;">getLine</span><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"Qual o seu nome ? "</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">7</span>		<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3ASystem+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">System</span></a>.<span style="color:#006600;">out</span>.<span style="color:#006600;">println</span><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"Escreveu : "</span>+input<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">8</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">9</span>
<span style="color:#cc66cc;">10</span>	<span style="color:#000000;font-weight:bold;">static</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">11</span>		<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3ASystem+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">System</span></a>.<span style="color:#006600;">loadLibrary</span><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"Prompt"</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">12</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">13</span><span style="color:#66cc66;"> }</span></pre>
<p>Em seguida vamos gerar o ficheiro Prompt.h que irá conter algo semelhante a este:</p>
<pre><span style="color:#cc66cc;">1</span> <span style="color:#808080;font-style:italic;">/* DO NOT EDIT THIS FILE - it is machine generated */</span>
<span style="color:#cc66cc;">2</span>	<span style="color:#339933;">#include &#60;jni.h&#62;</span>
<span style="color:#cc66cc;">3</span>	<span style="color:#808080;font-style:italic;">/* Header for class Prompt */</span>
<span style="color:#cc66cc;">4</span>
<span style="color:#cc66cc;">5</span>	<span style="color:#339933;">#ifndef _Included_Prompt</span>
<span style="color:#cc66cc;">6</span>	<span style="color:#339933;">#define _Included_Prompt</span>
<span style="color:#cc66cc;">7</span>	<span style="color:#339933;">#ifdef __cplusplus</span>
<span style="color:#cc66cc;">8</span>	<span style="color:#000000;font-weight:bold;">extern</span> <span style="color:#ff0000;">"C"</span> <span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">9</span>	<span style="color:#339933;">#endif</span>
<span style="color:#cc66cc;">10</span>	<span style="color:#808080;font-style:italic;">/*
11	* Class:     Prompt
12	* Method:    getLine
13	* Signature: (Ljava/lang/String;)Ljava/lang/String;
14	*/</span>
<span style="color:#cc66cc;">15</span>	JNIEXPORT jstring JNICALL Java_Prompt_getLine<span style="color:#66cc66;">(</span>JNIEnv *, jobject, jstring<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">16</span>
<span style="color:#cc66cc;">17</span>	<span style="color:#339933;">#ifdef __cplusplus</span>
<span style="color:#cc66cc;">18</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">19</span>	<span style="color:#339933;">#endif</span>
<span style="color:#cc66cc;">20</span>	<span style="color:#339933;">#endif</span></pre>
<p>Até aqui não há nada de novo relativamente ao HelloWorld implementado anteriormente, as novidades então agora na implementação do ficheiro Prompt.c que vai conter algumas novidade ao nível de JNI e no tratamento de Strings em JNI-C. Vamos então implementar o seguinte código.</p>
<pre><span style="color:#cc66cc;">1</span> <span style="color:#339933;">#include &#60;stdio.h&#62;</span>
<span style="color:#cc66cc;">2</span> <span style="color:#339933;">#include &#60;jni.h&#62;</span>
<span style="color:#cc66cc;">3</span> <span style="color:#339933;">#include "Prompt.h"</span>
<span style="color:#cc66cc;">4</span>
<span style="color:#cc66cc;">5</span> JNIEXPORT jstring JNICALL Java_Prompt_getLine<span style="color:#66cc66;">(</span>JNIEnv *env, jobject obj, jstring prompt<span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">6</span>
<span style="color:#cc66cc;">7</span>	<span style="color:#993333;">char</span> buf<span style="color:#66cc66;">[</span><span style="color:#cc66cc;">128</span><span style="color:#66cc66;">]</span>;
<span style="color:#cc66cc;">8</span>	<span style="color:#993333;">const</span> jbyte *str;
<span style="color:#cc66cc;">9</span>
<span style="color:#cc66cc;">10</span>	str = <span style="color:#66cc66;">(</span>*env<span style="color:#66cc66;">)</span>-&#62;GetStringUTFChars<span style="color:#66cc66;">(</span>env,prompt,<span style="color:#000000;font-weight:bold;">NULL</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">11</span>
<span style="color:#cc66cc;">12</span>	<span style="color:#b1b100;">if</span><span style="color:#66cc66;">(</span>str == <span style="color:#000000;font-weight:bold;">NULL</span><span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">13</span>		<span style="color:#b1b100;">return</span> <span style="color:#000000;font-weight:bold;">NULL</span>;
<span style="color:#cc66cc;">14</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">15</span>
<span style="color:#cc66cc;">16</span>	<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color:#000066;">printf</span></a><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"%s"</span>,str<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">17</span>	<span style="color:#66cc66;">(</span>*env<span style="color:#66cc66;">)</span>-&#62;ReleaseStringUTFChars<span style="color:#66cc66;">(</span>env,prompt,str<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">18</span>	scanf<span style="color:#66cc66;">(</span><span style="color:#ff0000;">"%s"</span>,buf<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">19</span>	<span style="color:#b1b100;">return</span> <span style="color:#66cc66;">(</span>*env<span style="color:#66cc66;">)</span>-&#62;NewStringUTF<span style="color:#66cc66;">(</span>env,buf<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">20</span> <span style="color:#66cc66;">}</span></pre>
<p>Como podemos ver na linha 5 nos argumentos do método para além das variáveis de ambiente que por defeito são colocadas, neste caso foi adicionada mais uma a variável prompt do tipo jstring que corresponde à String dada como argumento da classe Java. Como o C não tem o Objecto String como o Java vamos ter de passar a String para outra forma trabalhável em JNI-C, para isso é criada  uma variável apontador do tipo jbyte, que de uma forma básica é o byte do JNI da mesma forma que o jstring é a String do JNI. O passo final para fazer a conversão é usar a função do JNI GetStringUTFChar que retorna uma cópia da String dada no segundo argumento (linha 10) e assim a variável str vai ficar com o valor da String dado como argumento ao método getLine.<br />
Depois deste procedimento basta utilizar a função printf do C para imprimir a String e para terminar o processamento da String vamos usar a função  ReleaseStringUTFChars (linha 17) que vai libertar a memória usada para guardar a String, atenção que este método apenas deve ser utilizado depois de terem terminado todas as operações na String.<br />
Vamos agora para finalizar o nosso programa capturar o input do utilizador através da função scanf (linha 18) e guardar o input sob a forma de String no array de char definido na linha 7, em seguida basta converter o array de char para um Objecto String e retorná-lo para o Java, para isso vamos usar a função NewStringUTF como podemos ver na linha 19. Ao executar este exemplo o que vai acontecer será um intercâmbio de dados bastante simples, o Java envia uma String que é impressa pelo C, em seguida a função scanf vai capturar o input do utilizador e irá retornar esse input para o Java que o irá imprimir com o método println().</p>
<p>Passamos agora ao tratamento de arrays de Java para C, para isso vamos implementar o seguinte código.</p>
<pre><span style="color:#cc66cc;">1</span> <span style="color:#000000;font-weight:bold;">public</span> <span style="color:#000000;font-weight:bold;">class</span> IntArray<span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">2</span>
<span style="color:#cc66cc;">3</span>	<span style="color:#000000;font-weight:bold;">private</span> <span style="color:#000000;font-weight:bold;">native</span> <span style="color:#993333;">int</span> sumArray<span style="color:#66cc66;">(</span><span style="color:#993333;">int</span> <span style="color:#66cc66;">[</span><span style="color:#66cc66;">]</span> arr<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">4</span>
<span style="color:#cc66cc;">5</span>	<span style="color:#000000;font-weight:bold;">public</span> <span style="color:#000000;font-weight:bold;">static</span> <span style="color:#993333;">void</span> main<span style="color:#66cc66;">(</span><a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AString+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">String</span></a> args <span style="color:#66cc66;">[</span><span style="color:#66cc66;">]</span><span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">6</span>		IntArray p = <span style="color:#000000;font-weight:bold;">new</span> IntArray<span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">7</span>		<span style="color:#993333;">int</span> arr<span style="color:#66cc66;">[</span><span style="color:#66cc66;">]</span> = <span style="color:#000000;font-weight:bold;">new</span> <span style="color:#993333;">int</span><span style="color:#66cc66;">[</span><span style="color:#cc66cc;">10</span><span style="color:#66cc66;">]</span>;
<span style="color:#cc66cc;">8</span>		<span style="color:#b1b100;">for</span><span style="color:#66cc66;">(</span><span style="color:#993333;">int</span> i = <span style="color:#cc66cc;">0</span>; i &#60; <span style="color:#cc66cc;">10</span>; i++<span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">9</span>			arr<span style="color:#66cc66;">[</span>i<span style="color:#66cc66;">]</span> = i;
<span style="color:#cc66cc;">10</span>		<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">11</span>		<span style="color:#993333;">int</span> sum = p.<span style="color:#006600;">sumArray</span><span style="color:#66cc66;">(</span>arr<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">12</span>		<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3ASystem+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">System</span></a>.<span style="color:#006600;">out</span>.<span style="color:#006600;">println</span><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"sum = "</span>+ sum<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">13</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">14</span>
<span style="color:#cc66cc;">15</span>	<span style="color:#000000;font-weight:bold;">static</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">16</span>		<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3ASystem+java.sun.com&#38;btnI=I%27m%20Feeling%20Lucky"><span style="color:#aaaadd;font-weight:bold;">System</span></a>.<span style="color:#006600;">loadLibrary</span><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"IntArray"</span><span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">17</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">18</span> <span style="color:#66cc66;">}</span></pre>
<p>Como podemos ver o código implementado vai  criar um array com 10 posições e vai preenche las com os números de 0 a 9, em seguida vai executar o método nativo sumArray que vai somar todos os valores presentes no array e vai retornar o total da soma. Vamos agora passar à implementação do método nativo e para isso vamos começar como sempre por gerar o ficheiro IntArray.h.</p>
<pre><span style="color:#cc66cc;">1</span> <span style="color:#808080;font-style:italic;">/* DO NOT EDIT THIS FILE - it is machine generated */</span>
<span style="color:#cc66cc;">2</span>	<span style="color:#339933;">#include &#60;jni.h&#62;</span>
<span style="color:#cc66cc;">3</span>	<span style="color:#808080;font-style:italic;">/* Header for class IntArray */</span>
<span style="color:#cc66cc;">4</span>
<span style="color:#cc66cc;">5</span>	<span style="color:#339933;">#ifndef _Included_IntArray</span>
<span style="color:#cc66cc;">6</span>	<span style="color:#339933;">#define _Included_IntArray</span>
<span style="color:#cc66cc;">7</span>	<span style="color:#339933;">#ifdef __cplusplus</span>
<span style="color:#cc66cc;">8</span>	<span style="color:#000000;font-weight:bold;">extern</span> <span style="color:#ff0000;">"C"</span> <span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">9</span>	<span style="color:#339933;">#endif</span>
<span style="color:#cc66cc;">10</span>	<span style="color:#808080;font-style:italic;">/*
11	* Class:     IntArray
12 	* Method:    sumArray
13 	* Signature: ([I)I
14 	*/</span>
<span style="color:#cc66cc;">15</span>	JNIEXPORT jint JNICALL Java_IntArray_sumArray<span style="color:#66cc66;">(</span>JNIEnv *, jobject, jintArray<span style="color:#66cc66;">)</span>;
<span style="color:#cc66cc;">16</span>
<span style="color:#cc66cc;">17</span>	<span style="color:#339933;">#ifdef __cplusplus</span>
<span style="color:#cc66cc;">18</span>	<span style="color:#66cc66;">}</span>
<span style="color:#cc66cc;">19</span>	<span style="color:#339933;">#endif</span>
<span style="color:#cc66cc;">20</span>	<span style="color:#339933;">#endif</span></pre>
<p>Ao vermos os argumentos do método podemos verificar que está agora presente um jintArray que corresponde ao array de inteiros do Java que é dado como argumento na chamada do método. Agora o código nativo do nosso método.</p>
<pre><span style="color:#cc66cc;">1</span> <span style="color:#339933;">#include &#60;jni.h&#62;</span>
<span style="color:#cc66cc;">2</span> <span style="color:#339933;">#include &#60;stdio.h&#62;</span>
<span style="color:#cc66cc;">3</span> <span style="color:#339933;">#include "IntArray.h"</span>
<span style="color:#cc66cc;">4</span>
<span style="color:#cc66cc;">5</span> JNIEXPORT jint JNICALL Java_IntArray_sumArray<span style="color:#66cc66;">(</span>JNIEnv *env, jobject obj, jintArray arr<span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
<span style="color:#cc66cc;">6</span>
<span style="color:#cc66cc;">7</span>	jint *carr;
<span style="color:#cc66cc;">8</span>	jint i = <span style="color:#cc66cc;">0</span>;
<span style="color:#cc66cc;">9</span>	jint sum = <span style="color:#cc66cc;">0</span>;
<span style="color:#cc66cc;">10</span>     carr = <span style="color:#66cc66;">(</span>*env<span style="color:#66cc66;">)</span>-&#62;GetIntArrayElements<span style="color:#66cc66;">(</