<?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>Mon, 13 Oct 2008 11:20:27 +0000</pubDate>

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

<item>
<title><![CDATA[Cuba: God rewards a faithful prayer]]></title>
<link>http://joelnews.wordpress.com/?p=42</link>
<pubDate>Wed, 08 Oct 2008 19:33:15 +0000</pubDate>
<dc:creator>joelnews</dc:creator>
<guid>http://joelnews.fr.wordpress.com/2008/10/08/cuba-god-rewards-a-faithful-prayer/</guid>
<description><![CDATA[Last month the Methodist Church in Cuba inaugurated its new theological seminary in a quite special ]]></description>
<content:encoded><![CDATA[<p><span style="font-size:x-small;color:#333333;font-family:Verdana;">Last month the Methodist Church in Cuba inaugurated its new theological seminary in a quite special place - a massive building complex that once belonged to them, but that the government confiscated after the Communist revolution of the late 1950's.</span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[USA: Financial crisis could spark revival]]></title>
<link>http://joelnews.wordpress.com/?p=43</link>
<pubDate>Wed, 08 Oct 2008 19:33:06 +0000</pubDate>
<dc:creator>joelnews</dc:creator>
<guid>http://joelnews.fr.wordpress.com/2008/10/08/usa-financial-crisis-could-spark-revival/</guid>
<description><![CDATA[Is there a silver lining in the current financial crisis? A New York pastor believes the financial m]]></description>
<content:encoded><![CDATA[<p><span style="font-size:x-small;color:#333333;font-family:Verdana;">Is there a silver lining in the current financial crisis? A New York pastor believes the financial meltdown may be a tool God uses to spark revival in America's financial center and the rest of the nation.</span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Java Evaluation of Docbasic Expressions]]></title>
<link>http://doquent.wordpress.com/?p=87</link>
<pubDate>Mon, 22 Sep 2008 14:43:34 +0000</pubDate>
<dc:creator>doquent</dc:creator>
<guid>http://doquent.fr.wordpress.com/2008/09/22/java-evaluation-of-docbasic-expressions/</guid>
<description><![CDATA[Huh? Exactly. 
After an upgrade to SP5 from 5.3 SP3 we started getting regular crashes of Weblogic, ]]></description>
<content:encoded><![CDATA[<p>Huh? Exactly. </p>
<p>After an upgrade to SP5 from 5.3 SP3 we started getting regular crashes of Weblogic, which was hosting the WDK apps. After looking at various crashes we were still struggling to find something common among the crash instances. Finally, we discovered that every crash that left a dump file showed a stack trace of expression evaluation for conditional value assistance. It didn't indicate the expression it was evaluating but it did show that it was going outside the JVM via JNI and crashing there.</p>
<p>Fast forwarding to the EMC response. They had encountered something similar in another case and the recommendation was to migrate docbasic expressions to Java implementation! Huh?</p>
<p>Well, <em>Appendix B of DQL Reference</em> describes this process in a reasonable detail. Apparently, for evaluating the conditions in value assistance (among other things) DFC uses a DLL which is a Docbasic runtime. However, it is possible to provide a Java implementation for expressions so that the need for JNI calls can be obviated. The methods available for this purpose are called <code>dmc_MigrateDbExprsToJava</code> and <code>dmc_MigrateDbExprsToJavaForType</code>.</p>
<p>If you follow this documentation in conjunction with the object reference it will all begin to make sense. The only additional worthwhile thing to know, and probably the biggest value addition offered by this post, is the following.</p>
<p>Once you have created the Java implementations for Docbasic expressions, you can disable and enable the use of these Java implementations. However, when we tried to disable the use of these expressions using <code>dmc_SetJavaExprEnabled</code>, the command failed. When we got to the logs, we found various errors but one caught our eye. It complained about missing a parameter named "enabled". However, the reference names the parameter as "enable" (which turns out to be incorrect). Once we corrected the parameter name to be "enabled" in the command line, it started to work as expected.</p>
<p>In order to troubleshoot this issue, we wrote a small DFC client that iterated through docbase objects and exercised all the conditions present in value assistance. We embedded this client in a JSP so that we could reproduce it in the environment that was encountering the problem. Using this tool, we were able to reproduce the problem consistently. The tests following the change have been encouraging since we haven't seen any more crashes.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Hello World en JNI]]></title>
<link>http://qubits.wordpress.com/?p=20</link>
<pubDate>Tue, 16 Sep 2008 04:04:22 +0000</pubDate>
<dc:creator>miguelio</dc:creator>
<guid>http://qubits.fr.wordpress.com/2008/09/16/hello-world-en-jni/</guid>
<description><![CDATA[Como parte de mi proyecto de conectar pics de la serie 18 de microchip con java escribí este artíc]]></description>
<content:encoded><![CDATA[<p>Como parte de mi proyecto de conectar pics de la serie 18 de microchip con java escribí <a href="http://code.google.com/p/jmpusbapi/wiki/HelloWorld">este artículo </a>sobre como realizar un programa en java usando JNI:</p>
<p><strong>Introducción </strong></p>
<p>Este documento muestra como construir un Hello World usando JNI.</p>
<p>JNI es la sigla de "Java Native Interface" y como su nombre lo indica, es una interfaz que permite llamar a funciones compiladas en el código nativo de la máquina en que se está ejecutando el programa.</p>
<p>Para esto, primero debemos escribir la función en algún lenguaje y compilarla como una librería del entorno en el que vamos a llamarla. (Por ejemplo en Windows, podemos compilar una DLL en Visual C++ con las funciones que queremos llamar desde Java).</p>
<p><strong>Hello JNI World</strong></p>
<p>Antes que nada, si queremos usar JNI tenemos que poder compilar un ejemplo simple y verificar como funciona:</p>
<p><!--more--></p>
<h2>Mundo Java</h2>
<p>Se empieza por crear la clase Java definiendo la interfaz de comunicación con la futura DLL.</p>
<p> </p>
<p> </p>
<p style="padding-left:30px;"><em>import java.util.*;</em></p>
<p style="padding-left:30px;"><em><br />
</em></p>
<p style="padding-left:30px;"><em>class HelloWorld {</em></p>
<p style="padding-left:30px;"><em>//Native method declaration</em></p>
<p style="padding-left:30px;"><em>  native void sayHello(String name);</em></p>
<p style="padding-left:30px;"><em>//Load the library</em></p>
<p style="padding-left:30px;"><em>  static {</em></p>
<p style="padding-left:30px;"><em>    System.loadLibrary("helloworld");</em></p>
<p style="padding-left:30px;"><em>  }</em></p>
<p style="padding-left:30px;"><em><br />
</em></p>
<p style="padding-left:30px;"><em>  public static void main(String args[]) {</em></p>
<p style="padding-left:30px;"><em>//Create class instance</em></p>
<p style="padding-left:30px;"><em>    HelloWorld hello =new HelloWorld();</em></p>
<p style="padding-left:30px;"><em>//Call native method</em></p>
<p style="padding-left:30px;"><em>    hello.sayHello("Nerdy");</em></p>
<p style="padding-left:30px;"><em>  }</em></p>
<p style="padding-left:30px;"><em>}</em></p>
<p style="padding-left:30px;"> </p>
<p> </p>
<p>Compilar la clase con el comando "javac HelloWorld.java"</p>
<p> </p>
<p>Luego ejecutar el comando "javah HelloWorld". Se generará un header HelloWorld.h que contiene la descripción de los métodos que debería implementar la libería dll:</p>
<p> </p>
<p style="padding-left:30px;"><em>/* DO NOT EDIT THIS FILE - it is machine generated */<br />
</em></p>
<p style="padding-left:30px;"><em>#include &#60;jni.h&#62;</em></p>
<p style="padding-left:30px;"><em>/* Header for class HelloWorld */</em></p>
<p style="padding-left:30px;"><em><br />
</em></p>
<p style="padding-left:30px;"><em>#ifndef _Included_HelloWorld</em></p>
<p style="padding-left:30px;"><em>#define _Included_HelloWorld</em></p>
<p style="padding-left:30px;"><em>#ifdef __cplusplus</em></p>
<p style="padding-left:30px;"><em>extern "C" {</em></p>
<p style="padding-left:30px;"><em>#endif</em></p>
<p style="padding-left:30px;"><em>/*</em></p>
<p style="padding-left:30px;"><em> * Class:     HelloWorld</em></p>
<p style="padding-left:30px;"><em> * Method:    sayHello</em></p>
<p style="padding-left:30px;"><em> * Signature: (Ljava/lang/String;)V</em></p>
<p style="padding-left:30px;"><em> */</em></p>
<p style="padding-left:30px;"><em>JNIEXPORT void JNICALL Java_HelloWorld_sayHello</em></p>
<p style="padding-left:30px;"><em>  (JNIEnv *, jobject, jstring);</em></p>
<p style="padding-left:30px;"><em><br />
</em></p>
<p style="padding-left:30px;"><em>#ifdef __cplusplus</em></p>
<p style="padding-left:30px;"><em>}</em></p>
<p style="padding-left:30px;"><em>#endif</em></p>
<p style="padding-left:30px;"><em>#endif</em></p>
<p style="padding-left:30px;"> </p>
<p> </p>
<h2>Mundo C</h2>
<p>Cómo paso siguiente vamos a implementar la función en C++ (en realidad en C, porque no vamos a crear ninguna clase) para Visual C++ de esta manera:</p>
<p> </p>
<p style="padding-left:30px;"><em>#include &#60;jni.h&#62;<br />
</em></p>
<p style="padding-left:30px;"><em>#include "HelloWorld.h"</em></p>
<p style="padding-left:30px;"><em>#include &#60;stdio.h&#62;</em></p>
<p style="padding-left:30px;"><em><br />
</em></p>
<p style="padding-left:30px;"><em>JNIEXPORT void JNICALL </em></p>
<p style="padding-left:30px;"><em>Java_HelloWorld_sayHello(JNIEnv *env, jobject obj, jstring name)</em></p>
<p style="padding-left:30px;"><em>{</em></p>
<p style="padding-left:30px;"><em>  jboolean iscopy;</em></p>
<p style="padding-left:30px;"><em>  const char *charsname = (*env)-&#62;GetStringUTFChars(</em></p>
<p style="padding-left:30px;"><em>                env, name, &#38;iscopy);</em></p>
<p style="padding-left:30px;"><em>  printf("Hello ");</em></p>
<p style="padding-left:30px;"><em>  printf(charsname);</em></p>
<p style="padding-left:30px;"><em>  printf(", this is your first JNI library\n");</em></p>
<p style="padding-left:30px;"><em>  return;</em></p>
<p style="padding-left:30px;"><em>}</em></p>
<p style="padding-left:30px;"> </p>
<p> </p>
<p>Algunas observaciones:</p>
<p> * <em>#include &#60;jni.h&#62;</em>: Esta línea es necesaria para poder usar las funciones de JNI dentro de la DLL. JNI implementa "métodos" y constantes para comunicarse con Java, por ejemplo para convertir tipos de datos. </p>
<p> * <em>JNIEXPORT void JNICALL</em>: Esta línea es un ejemplo del uso de definiciones JNI para código C, indica como se exporta la función en la dll y el método de llamada a la misma. Lo único que nos importa es que tiene que ir así.</p>
<p> * <em>JNIEnv *env</em>: Este es un puntero al objeto environment de JNI. Con los métodos de este objeto hacemos por ejemplo transformaciones de formato de los parámetros. Además es un handler al thread actual de la máquina virtual de java.</p>
<p> * <em>jobject obj</em> : Esta es la referencia al método de Java que llama a la función. Supongo que sirve para hacer recursión. Si el método que hace la llamada es estático viene un jclass.</p>
<p> * <em>jstring</em>: La clase String de Java no existe en C++, hay que hacer una conversión para poder usar los datos. Esto se hace en la línea <em>const char *charsname = (*env)-&#62;GetStringUTFChars(env, name, &#38;iscopy);</em> donde <em>*charsname</em> es un puntero a un char que en realidad apunta a una cadena de caracteres (ver pointers en C) y el operador <em>-&#62;</em> es como el punto "." en Java pero para objetos referenciados por puntero (el tipo env de era <em>JNIEnv*</em> y por eso hay que usarlo).</p>
<p> </p>
<p>Por último, una vez está escrito el código hay que compilar. La forma más fácil de hacer esto (si la DLL está compuesta de un único archivo .c) es compilarla directamente desde linea de comandos. Para eso hay que abrir "Simbolo de Sistema de Visual Studio". Esto despliega una nostálgica ventana de DOS donde se puede ejecutar el comando para generar la librería. No lo hacemos con la línea de comandos común y corriente (ejecutando cmd) porque haría falta setear muchas variables de entorno de Visual Studio.</p>
<p> </p>
<p>Lo mejor para compilar es meter el comando dentro de un archivo .bat para poder usar la variable de entorno %JAVA_HOME% que apunta al directorio del JDK. Dentro de este la carpeta include contiene el archivo "jni.h" al que se hace referencia desde el código de la DLL. Luego desde la consola de Visual Studio llamamos a nuestro script (por ejemplo makeDLL.bat).</p>
<p> </p>
<p>El comando dentro del archivo makeDLL.bat es:</p>
<p> </p>
<p>cl -I%JAVA_HOME%/include -I%JAVA_HOME%/include/win32 -LD HelloWorld.c -Fehelloworld.dll</p>
<p> </p>
<p>La opción -I incluye al directorio para buscar los includes, -LD indica el archivo fuente con el que creará una DLL y por último -Fe indica el nombre del archivo de salida.</p>
<p>Esto generará el archivo HelloWorld.dll y sus correspondientes HelloWorld.obj y HelloWorld.lib que no nos sirven para nada y se pueden borrar.</p>
<p> </p>
<p>Finalmente, para probar el programa ejecutamos "java HelloWorld" y obtenemos la siguiente salida:</p>
<p> </p>
<p style="padding-left:30px;"><em><strong>Hello Nerdy, this is your first JNI library</strong></em></p>
<p> </p>
<h2>Conclusión</h2>
<p>A esta altura creo que se habrán dado cuenta de que JNI no es fácil. No es algo trivial (sobre todo si piensan en objetos complejos y threads). </p>
<p>Este fue uno de los HelloWorld más complicados que ví en mi vida. Por suerte hay bastante buena documentación en Internet:</p>
<p> * Introductoria: <a href="http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html">http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html</a> de acá saqué en parte las cosas para hacer el HelloWorld</p>
<p> * Más completo: <a href="http://java.sun.com/docs/books/jni/">Java Native Interface: Programmer's Guide and Specification</a>. Se puede bajar el libro en html o pdf o verlo en línea.</p>
<p> * Especificación completa: <a href="http://java.sun.com/javase/6/docs/technotes/guides/jni/index.html">http://java.sun.com/javase/6/docs/technotes/guides/jni/index.html</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Calendario de Actividades, JNI Septiembre]]></title>
<link>http://2jni.wordpress.com/?p=3</link>
<pubDate>Sun, 31 Aug 2008 22:05:32 +0000</pubDate>
<dc:creator>critaco</dc:creator>
<guid>http://2jni.fr.wordpress.com/2008/08/31/calendario-de-actividades-jni-septiembre/</guid>
<description><![CDATA[Actividades 
Septiembre:

sabado 6:
Culto compañerismo
lugar: en la iglesia
hora: 6.30 p.m.
organiz]]></description>
<content:encoded><![CDATA[<h1 style="color:#800000;"><strong><span style="color:#008000;">Acti</span><span style="color:#ffffff;">vid</span><span style="color:#ff0000;">ades</span> </strong></h1>
<h1 style="color:#800000;"><strong><span style="color:#008000;">Sept</span><span style="color:#ffffff;">iem</span><span style="color:#ff0000;">bre:</span></strong></h1>
<p><!--more--></p>
<h2 style="color:#339966;">sabado 6:</h2>
<h2 style="color:#339966;">Culto compañerismo<br />
lugar: en la iglesia<br />
hora: 6.30 p.m.<br />
organizado  por: Katy<br />
objetivo: integracion de grupos de amistad juvenil</h2>
<h2 style="color:#339966;">sabado  13:</h2>
<h2 style="color:#339966;">Paseo a la alberca<br />
lugar: pendiente<br />
hora: 10 am. a 2  pm.</h2>
<h2 style="color:#ffffff;">domingo 14:</h2>
<h2 style="color:#ffffff;">Celebracion de noche mexicana<br />
lugar: en la  iglesia<br />
objetivo: trabajo en GAJ</h2>
<h2 style="color:#ffffff;">lunes 15 y martes 16:</h2>
<h2 style="color:#ffffff;">Congreso de  adolescentes interzonas valles y frailesca<br />
lugar: villas el Buen  Pastor<br />
costo: 150 pesos por persona</h2>
<h2 style="color:#ff0000;">sabado 20:</h2>
<h2 style="color:#ff0000;">Retiro  espiritual<br />
lugar: el Eden<br />
hora: 9.00 am.<br />
nota: ir en  ayuno</h2>
<h2 style="color:#ff0000;">sabado 27:</h2>
<h2 style="color:#ff0000;">Culto normal<br />
lugar: iglesia<br />
hor: 6.30 p.m.</h2>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Links compilados durante la última semana]]></title>
<link>http://qubits.wordpress.com/?p=18</link>
<pubDate>Tue, 19 Aug 2008 03:06:06 +0000</pubDate>
<dc:creator>miguelio</dc:creator>
<guid>http://qubits.fr.wordpress.com/2008/08/19/links-compilados-durante-la-ultima-semana/</guid>
<description><![CDATA[Les dejo un resumen de los links a los sitios más útiles que encontre la semana pasada, junto a un]]></description>
<content:encoded><![CDATA[<p>Les dejo un resumen de los links a los sitios más útiles que encontre la semana pasada, junto a una breve descripción del contenido.</p>
<p><a href="http://noti-tech.blogspot.com/2006/08/test-vocacionales-online.html">Tests Vocacionales Online</a>: Entrada en un blog de Blogger con links a varios tests vocacionales online. Algunos links rotos, otros apuntan a tests muy buenos. Ya estoy grande para estas cosas pero tenía que pasárselos a un conocido...</p>
<p><a href="http://www.cafeconleche.org/XOM/">XOM XML Parser</a><strong>: </strong>Parser y modelo de objetos de XML. Lo pienso utilizar para levantar documentos KML de Google Earth en el contexto de un trabajo de investigación sobre Sistemas de Información Geográfica(GIS).</p>
<p><a href="http://java.sun.com/docs/books/jni/html/titlepage.html">The Java Native Inteface Guide and Specification</a><strong>: </strong>Sitio oficial de sun con la guía de desarrollo JNI. Muy completo. Lo voy a utilizar en un proyecto para crear una interfaz entre dispositivos USB y Java desde Windows.</p>
<p><a href="http://picmania.garcia-cuervo.com/USB_MPUSBAPI_DLL.php">MPUSBAPI Library</a><strong>: </strong>Especificación (no oficial) del api (DLL en windows) para comunicar con dispositivos USB de Microchip.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JNI #2 - Stawiamy JVM]]></title>
<link>http://zenedith.wordpress.com/?p=78</link>
<pubDate>Thu, 31 Jul 2008 20:07:06 +0000</pubDate>
<dc:creator>zenedith</dc:creator>
<guid>http://zenedith.fr.wordpress.com/2008/07/31/jni-2-stawiamy-jvm/</guid>
<description><![CDATA[Pierwszą część mamy już za sobą. Potrafimy już tworzyć skomplikowane skrypty w Javie i korzy]]></description>
<content:encoded><![CDATA[<p>Pierwszą część mamy już za sobą. Potrafimy już tworzyć skomplikowane skrypty w Javie i korzystać z natywnego wsparcia ze strony cpp. Pozostaje więc teraz cały proces odpalić z exe..Stworzymy teraz aplikację startującą <em>JVM </em>i nasze skrypty - otrzymamy więc możliwość stworzenia "silnia gry" z Javą jako językiem skryptowym! Do dzieła.<!--more--></p>
<p>Na początek wypadałoby stworzyć kod w Javie, który będzie startował cały skrypt w Javie - może to być jakaś ogólna klasa typy Game, która tworzy resztę managerów i logikę gry.<br />
"Wołanie" metod statycznych z Javy jest bardzo proste z tego powodu, że nie musimy mieć instancji(obiektu) danej klasy. I na tym się właśnie zatrzymamy w tej części tutoriala.<br />
Załóżmy więc, że mamy taki kod:</p>
<pre class="geshi"><span style="color:#a1a100;">import java.awt.event.WindowAdapter;</span>
<span style="color:#a1a100;">import java.awt.event.WindowEvent;</span>

<span style="color:#a1a100;">import javax.swing.JFrame;</span>
<span style="color:#a1a100;">import javax.swing.UIManager;</span>

<span style="font-weight:bold;color:#000000;">public</span> <span style="font-weight:bold;color:#000000;">class</span> Game <span style="color:#66cc66;">{</span>

<span style="font-weight:bold;color:#000000;">public</span> <span style="font-weight:bold;color:#000000;">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;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">String</span></a><span style="color:#66cc66;">[</span><span style="color:#66cc66;">]</span> args<span style="color:#66cc66;">)</span> <span style="color:#66cc66;">{</span>
<span style="font-style:italic;color:#808080;">//rusza nasza logika..</span>

	<span style="font-weight:bold;color:#000000;">try</span> <span style="color:#66cc66;">{</span>
		<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AUIManager+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">UIManager</span></a>.<span style="color:#006600;">setLookAndFeel</span><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"com.sun.java.swing.plaf.windows.WindowsLookAndFeel"</span><span style="color:#66cc66;">)</span>;

		<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AJFrame+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">JFrame</span></a> jFrame = <span style="font-weight:bold;color:#000000;">new</span> <a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AJFrame+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">JFrame</span></a><span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;
		jFrame.<span style="color:#006600;">addWindowListener</span><span style="color:#66cc66;">(</span>
		<span style="font-weight:bold;color:#000000;">new</span> <a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AWindowAdapter+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">WindowAdapter</span></a><span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>
		<span style="color:#66cc66;">{</span>
			<span style="font-weight:bold;color:#000000;">public</span> <span style="color:#993333;">void</span> windowClosing<span style="color:#66cc66;">(</span><a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AWindowEvent+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">WindowEvent</span></a> e<span style="color:#66cc66;">)</span>
			<span style="color:#66cc66;">{</span>
			<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3ASystem+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">System</span></a>.<span style="color:#006600;">exit</span><span style="color:#66cc66;">(</span><span style="color:#cc66cc;">0</span><span style="color:#66cc66;">)</span>;
			<span style="color:#66cc66;">}</span>
		<span style="color:#66cc66;">}</span>
		<span style="color:#66cc66;">)</span>;

		jFrame.<span style="color:#006600;">setSize</span><span style="color:#66cc66;">(</span><span style="color:#cc66cc;">400</span>, <span style="color:#cc66cc;">300</span><span style="color:#66cc66;">)</span>;
		jFrame.<span style="color:#006600;">setVisible</span><span style="color:#66cc66;">(</span><span style="font-weight:bold;color:#000000;">true</span><span style="color:#66cc66;">)</span>;

	<span style="color:#66cc66;">}</span> <span style="font-weight:bold;color:#000000;">catch</span> <span style="color:#66cc66;">(</span><a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AException+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">Exception</span></a> e<span style="color:#66cc66;">)</span> <span style="color:#66cc66;">{</span>
		e.<span style="color:#006600;">printStackTrace</span><span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;
	<span style="color:#66cc66;">}</span> <span style="font-weight:bold;color:#000000;">catch</span> <span style="color:#66cc66;">(</span><a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AThrowable+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">Throwable</span></a> t<span style="color:#66cc66;">)</span> <span style="color:#66cc66;">{</span>
		t.<span style="color:#006600;">printStackTrace</span><span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;
	<span style="color:#66cc66;">}</span>
<span style="color:#66cc66;">}</span>

<span style="font-weight:bold;color:#000000;">public</span> <span style="font-weight:bold;color:#000000;">static</span> <span style="color:#993333;">int</span> GetInt<span style="color:#66cc66;">(</span><span style="color:#993333;">int</span> n<span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
	<span style="font-weight:bold;color:#000000;">return</span> n*n;
<span style="color:#66cc66;">}</span>

<span style="font-weight:bold;color:#000000;">public</span> <span style="font-weight:bold;color:#000000;">static</span> <span style="color:#993333;">int</span> GetVersion<span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>
	<span style="font-weight:bold;color:#000000;">return</span> <span style="color:#cc66cc;">1</span>;
<span style="color:#66cc66;">}</span>

<span style="color:#66cc66;">}</span></pre>
<p>Zauważmy, że wszystkie metody są statyczne oraz dobrane tak, żeby pokazać kluczowe różnice w ich wywoływaniu z poziomu cpp.<br />
Teraz przejdźmy do naszego projektu w cpp - tworzymy nowy, pusty projekt c++ wg poprzednio podanych schematów. Tym razem musimy zrobić następujące czynnoś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>wybieramy pole <strong>Libraries </strong>i uzupełniamy obie rubryki: w górej wpisujemy nazwę biblioteki statycznej którą musimy dołączyć do projektu ze względu na <em>JVM </em>- wpisujemy <strong>jvm </strong>(bez rozszerzenia), natomiast w dolnej musimy wskazać katalog zawierający tą bibliotekę (<strong>\lib</strong> w katalogu zainstalowanego JDK - u mnie <em>D:\Program Files\Java\jdk1.6.0_06\lib</em>),</li>
<li>zatwierdzamy wprowadzone zmiany i powracamy do ekranu głównego.</li>
</ul>
<p style="text-align:center;"><a href="http://zenedith.wordpress.com/files/2008/07/lib.jpg"><img class="alignnone size-thumbnail wp-image-76" src="http://zenedith.wordpress.com/files/2008/07/lib.jpg?w=128" alt="" width="128" height="95" /></a></p>
<p>Dodajemy do projektu pliki implementacji - w naszym przypadku wystarczy jeden, który wystartuje <em>JVM </em>- np. main.cpp. Jego treść jest u mnie następująca:</p>
<pre class="geshi"><span style="color:#339900;">#include &#60;jni.h&#62;</span>
<span style="color:#339900;">#include &#60;conio.h&#62;</span>
<span style="color:#339900;">#include &#60;memory.h&#62;</span>

<span style="color:#0000cc;">int</span> main<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
JavaVMOption options<span style="color:#000000;">[</span><span style="color:#0000dd;">1</span><span style="color:#000000;">]</span>;
JNIEnv *env;
JavaVM *jvm;
JavaVMInitArgs vm_args;
<span style="color:#0000cc;">long</span> status;
jclass cls;
jmethodID mid;
jint square;

options<span style="color:#000000;">[</span><span style="color:#0000dd;">0</span><span style="color:#000000;">]</span>.<span style="color:#bb00cc;">optionString</span> = <span style="color:#666666;">"-Djava.class.path=."</span>;
<span style="color:#0000dd;">memset</span><span style="color:#000000;">(</span>&#38;vm_args, <span style="color:#0000dd;">0</span>, <span style="color:#0000dd;">sizeof</span><span style="color:#000000;">(</span>vm_args<span style="color:#000000;">)</span><span style="color:#000000;">)</span>;
vm_args.<span style="color:#bb00cc;">version</span> = JNI_VERSION_1_4;
vm_args.<span style="color:#bb00cc;">nOptions</span> = <span style="color:#0000dd;">1</span>;
vm_args.<span style="color:#bb00cc;">options</span> = options;
status = JNI_CreateJavaVM<span style="color:#000000;">(</span>&#38;jvm, <span style="color:#000000;">(</span><span style="color:#0000cc;">void</span>**<span style="color:#000000;">)</span>&#38;env, &#38;vm_args<span style="color:#000000;">)</span>;

<span style="color:#0000cc;">if</span> <span style="color:#000000;">(</span>status != JNI_ERR<span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
<span style="color:#0000dd;">printf</span><span style="color:#000000;">(</span><span style="color:#666666;">"jvm ok<span style="font-weight:bold;color:#666666;">\n</span>"</span><span style="color:#000000;">)</span>;

cls = env-&#62;FindClass<span style="color:#000000;">(</span><span style="color:#666666;">"Game"</span><span style="color:#000000;">)</span>;
<span style="color:#0000cc;">if</span><span style="color:#000000;">(</span>cls !=<span style="color:#0000dd;">0</span><span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
<span style="color:#0000dd;">printf</span><span style="color:#000000;">(</span><span style="color:#666666;">"class Game ok<span style="font-weight:bold;color:#666666;">\n</span>"</span><span style="color:#000000;">)</span>;

mid = env-&#62;GetStaticMethodID<span style="color:#000000;">(</span> cls, <span style="color:#666666;">"GetInt"</span>, <span style="color:#666666;">"(I)I"</span><span style="color:#000000;">)</span>;
<span style="color:#0000cc;">if</span><span style="color:#000000;">(</span>mid !=<span style="color:#0000dd;">0</span><span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
square = env-&#62;CallStaticIntMethod<span style="color:#000000;">(</span>cls, mid, <span style="color:#0000dd;">5</span><span style="color:#000000;">)</span>;
<span style="color:#0000dd;">printf</span><span style="color:#000000;">(</span><span style="color:#666666;">"GetInt: %d<span style="font-weight:bold;color:#666666;">\n</span>"</span>, square<span style="color:#000000;">)</span>;
<span style="color:#000000;">}</span>

mid = env-&#62;GetStaticMethodID<span style="color:#000000;">(</span> cls, <span style="color:#666666;">"GetVersion"</span>, <span style="color:#666666;">"()I"</span><span style="color:#000000;">)</span>;
<span style="color:#0000cc;">if</span><span style="color:#000000;">(</span>mid !=<span style="color:#0000dd;">0</span><span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
square = env-&#62;CallStaticIntMethod<span style="color:#000000;">(</span>cls, mid<span style="color:#000000;">)</span>;
<span style="color:#0000dd;">printf</span><span style="color:#000000;">(</span><span style="color:#666666;">"GetVersion: %d<span style="font-weight:bold;color:#666666;">\n</span>"</span>, square<span style="color:#000000;">)</span>;
<span style="color:#000000;">}</span>

mid = env-&#62;GetStaticMethodID<span style="color:#000000;">(</span> cls, <span style="color:#666666;">"main"</span>,<span style="color:#666666;">"([Ljava/lang/String;)V"</span><span style="color:#000000;">)</span>;

<span style="color:#0000cc;">if</span><span style="color:#000000;">(</span>mid !=<span style="color:#0000dd;">0</span><span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
<span style="color:#0000dd;">printf</span><span style="color:#000000;">(</span><span style="color:#666666;">"method main ok<span style="font-weight:bold;color:#666666;">\n</span>"</span><span style="color:#000000;">)</span>;

jclass string = env-&#62;FindClass<span style="color:#000000;">(</span><span style="color:#666666;">"java/lang/String"</span><span style="color:#000000;">)</span>;
jobjectArray args = env-&#62;NewObjectArray<span style="color:#000000;">(</span><span style="color:#0000dd;">0</span>,string, <span style="color:#0000cc;">NULL</span><span style="color:#000000;">)</span>;

env-&#62;CallStaticIntMethod<span style="color:#000000;">(</span>cls, mid, args<span style="color:#000000;">)</span>;
<span style="color:#000000;">}</span>
<span style="color:#000000;">}</span>

jvm-&#62;DestroyJavaVM<span style="color:#000000;">(</span><span style="color:#000000;">)</span>;
<span style="color:#0000cc;">return</span> <span style="color:#0000dd;">0</span>;
<span style="color:#000000;">}</span>
<span style="color:#0000cc;">else</span><span style="color:#000000;">{</span>
<span style="color:#0000dd;">printf</span><span style="color:#000000;">(</span><span style="color:#666666;">"jvm problem"</span><span style="color:#000000;">)</span>;
<span style="color:#0000cc;">return</span> <span style="color:#0000dd;">-1</span>;
<span style="color:#000000;">}</span>

<span style="color:#000000;">}</span></pre>
<p>Teraz będę opowiadał o tym co się w nim dzieje.<br />
Na starcie występuje deklaracja zmiennych, które za chwilę będą użyte do tworzenia <em>JVM</em>. Przejdźmy więc od razu do linii ustawiającej opcje <em>JVM</em>:</p>
<p><em>options[0].optionString = "-Djava.class.path=.";</em></p>
<p>Definiuje ona ścieżkę, gdzie <em>JVM </em>będzie szukać naszej klasy - u mnie widnieje . (kropka) a więc będzie szukać w katalogu projektu (cpp). Możemy tu oczywiście dodać parę ścieżek, rozdzielonych średnikiem (windows) lub dwukropkiem (linux,mac). Ponieważ jest to tablica opcji (o zadeklarowanym wymiarze 1) to nasza opcja ma indeks 0. Gdybyśmy chcieli zwiększyć ilość opcji to musimy to uwzględnić w miejscu deklaracji zmiennej <em>options</em> oraz parę linii niżej, gdzie podajemy ich liczbę raz jeszcze, już bezpośrednio (<em>vm_args.nOptions = 1;</em>).</p>
<p>Przejdźmy teraz do linii zawierającej następujący wpis:<br />
<em>vm_args.version = JNI_VERSION_1_4;</em><br />
Jest to dość kłopotliwa stała, ponieważ jeśli ją źle podamy to nie nastąpi stworzenie <em>JVM</em>. Jeśli będziemy kompilować nasz kod z wykorzystaniem JDK6, wartość ta powinna być ustawiona na <strong>JNI_VERSION_1_6</strong>, ja natomiast kompilowałem z użyciem JDK1.4 i JDK6 (co można zmienić w opcjach projektu Javy lub globalnie w opcjach Eclipse) i działa z JNI_VERSION_1_4.<br />
Do momentu szukania pierwszej metody wszystko powinno być jasne. Zobaczmy więc pierwszy przykład:</p>
<p><em>mid = env-&#62;GetStaticMethodID( cls, "GetInt", "(I)I");</em></p>
<p>Mówi on tak: <em>znajdź mi "wzór" metody statycznej z określonej wcześniej klasy o nazwie "GetInt", która pobiera parametr typu int i zwraca wynik typu int.</em><br />
Jeśli znaleziono, mamy kolejną linię:</p>
<p><em>square = env-&#62;CallStaticIntMethod(cls, mid, 5);</em></p>
<p>której tłumaczenie jest następujące: wywołaj metodę statyczną zwracającą int z określonej wcześniej klasy i "wzorca" metody i przekaż jej parametr 5 (int).Wynik zapisz do zmiennej <em>square</em>.<br />
To teraz w skrócie dwa kolejne przykłady:</p>
<p><em>mid = env-&#62;GetStaticMethodID( cls, "GetVersion", "()I");<br />
square = env-&#62;CallStaticIntMethod(cls, mid);</em></p>
<p>co tłumaczymy jako: znajdź "wzór" metody statycznej o nazwie "GetVersion" nie pobierającej żadnego parametru (pusty nawias zamiast V jak void!) i zwracającą wynik typu int. Wywołaj metodę z tego "wzorca" i zapisz wynik do zmiennej <em>square</em>.<br />
Na zakończenie metoda main z Javy:</p>
<p><em>mid = env-&#62;GetStaticMethodID( cls, "main","([Ljava/lang/String;)V");<br />
jclass string = env-&#62;FindClass("java/lang/String");<br />
jobjectArray args = env-&#62;NewObjectArray(0,string, NULL);<br />
env-&#62;CallStaticIntMethod(cls, mid, args);</em></p>
<p>Zaczynamy od poszukiwania "wzorca", podając że chodzi nam o metodę statyczną o nazwie "main", przyjmującą parametr typu String i nic nie zwracającej (V od void). Następnie musimy znaleźć "wzorzec" klasy String, który zostanie użyty do utworzenia pustej tablicy obiektów typu String, a następnie przekazanej do wywołania metody.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JNI #1 - 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.fr.wordpress.com/2008/07/23/jni-eclipse-cdt-mingw/</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.<!--more--></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>
<pre class="geshi"><span style="font-weight:bold;color:#000000;">public</span> <span style="font-weight:bold;color:#000000;">class</span> SomeData <span style="color:#66cc66;">{</span>

<span style="font-weight:bold;color:#000000;">native</span> <a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AString+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">String</span></a> GetVersion<span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;
<span style="font-weight:bold;color:#000000;">native</span> <span style="color:#993333;">void</span> SetVersion<span style="color:#66cc66;">(</span><a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AString+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">String</span></a> sNewVersion<span style="color:#66cc66;">)</span>;
<span style="font-weight:bold;color:#000000;">native</span> <span style="color:#993333;">void</span> DoSomething<span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;

<span style="font-weight:bold;color:#000000;">static</span><span style="color:#66cc66;">{</span>

<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3ASystem+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">System</span></a>.<span style="color:#006600;">loadLibrary</span><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"libjni_test"</span><span style="color:#66cc66;">)</span>;

<span style="color:#66cc66;">}</span>

<span style="font-weight:bold;color:#000000;">public</span> <a href="http://www.google.com/search?hl=en&#38;q=allinurl%3AString+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">String</span></a> GetSomeDataFromJava<span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span><span style="color:#66cc66;">{</span>

<span style="font-weight:bold;color:#000000;">return</span> <span style="color:#ff0000;">"dane z javy"</span>;

<span style="color:#66cc66;">}</span>

<span style="font-weight:bold;color:#000000;">public</span> <span style="font-weight:bold;color:#000000;">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;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">String</span></a><span style="color:#66cc66;">[</span><span style="color:#66cc66;">]</span> args<span style="color:#66cc66;">)</span> <span style="color:#66cc66;">{</span>

SomeData cData = <span style="font-weight:bold;color:#000000;">new</span> SomeData<span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span>;
<a href="http://www.google.com/search?hl=en&#38;q=allinurl%3ASystem+java.sun.com&#38;bntI=I%27m%20Feeling%20Lucky"><span style="font-weight:bold;color:#aaaadd;">System</span></a>.<span style="color:#006600;">out</span>.<span style="color:#006600;">println</span><span style="color:#66cc66;">(</span><span style="color:#ff0000;">"Version: "</span>+cData.<span style="color:#006600;">GetVersion</span><span style="color:#66cc66;">(</span><span style="color:#66cc66;">)</span><span style="color:#66cc66;">)</span>;

<span style="color:#66cc66;">}</span>

<span style="color:#66cc66;">}</span></pre>
<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 style="text-align:center;"><a href="http://zenedith.wordpress.com/files/2008/07/perspective.jpg"><img class="alignnone size-thumbnail wp-image-49" src="http://zenedith.wordpress.com/files/2008/07/perspective.jpg?w=128" alt="" width="128" height="77" /></a> <a href="http://zenedith.wordpress.com/files/2008/07/new_cpp_project.jpg"><img class="alignnone size-thumbnail wp-image-50" src="http://zenedith.wordpress.com/files/2008/07/new_cpp_project.jpg?w=128" alt="" width="128" height="76" /></a> <a href="http://zenedith.wordpress.com/files/2008/07/project_type.jpg"><img class="alignnone size-thumbnail wp-image-51" src="http://zenedith.wordpress.com/files/2008/07/project_type.jpg?w=86" alt="" width="86" height="96" /></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 style="text-align:center;"><a href="http://zenedith.wordpress.com/files/2008/07/properties.jpg"><img class="alignnone size-thumbnail wp-image-53" src="http://zenedith.wordpress.com/files/2008/07/properties.jpg?w=56" alt="" width="56" height="96" /></a> <a href="http://zenedith.wordpress.com/files/2008/07/tools_settings.jpg"><img class="alignnone size-thumbnail wp-image-54" src="http://zenedith.wordpress.com/files/2008/07/tools_settings.jpg?w=102" alt="" width="102" height="96" /></a> <a href="http://zenedith.wordpress.com/files/2008/07/artifact1.jpg"><img class="alignnone size-thumbnail wp-image-56" src="http://zenedith.wordpress.com/files/2008/07/artifact1.jpg?w=102" alt="" width="102" height="96" /></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 />
</code></p>
<pre class="geshi">JNIEXPORT jstring JNICALL Java_SomeData_GetVersion<span style="color:#000000;">(</span>JNIEnv * env, jobject o<span style="color:#000000;">)</span><span style="color:#000000;">{</span>
<span style="color:#0000cc;">const</span> <span style="color:#0000cc;">char</span> *str = <span style="color:#666666;">"1.1 MinGW compiled"</span>;
<span style="color:#0000cc;">return</span> env-&#62;NewStringUTF<span style="color:#000000;">(</span>str<span style="color:#000000;">)</span>;
<span style="color:#000000;">}</span></pre>
<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.<br />
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.fr.wordpress.com/2008/06/21/call-native-cc-functions-from-java-using-jni/</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.fr.wordpress.com/2008/06/19/getting-a-class-started-with-jni-part-4-writing-native-methods/</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.fr.wordpress.com/2008/06/16/jni-calling-cc-code-from-java-programs/</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.fr.wordpress.com/2008/06/15/getting-a-class-started-with-jni-part-3-native-methods-using-registernatives/</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.fr.wordpress.com/2008/06/11/getting-a-class-started-with-jni-part-2-native-methods-using-javah/</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[USA: Megachurches grow with 10 percent]]></title>
<link>http://joelnews.wordpress.com/?p=40</link>
<pubDate>Wed, 01 Oct 2008 19:33:30 +0000</pubDate>
<dc:creator>joelnews</dc:creator>
<guid>http://joelnews.fr.wordpress.com/2008/10/01/usa-megachurches-grow-with-10-percent/</guid>
<description><![CDATA[Megachurches in the United States of America have grown on average 10 percent compared to last year.]]></description>
<content:encoded><![CDATA[<p><span style="font-size:x-small;color:#333333;font-family:Verdana;">Megachurches in the United States of America have grown on average 10 percent compared to last year. This is reported by Outreach magazine in its annual report of the 100 largest and fastest-growing churches in America.</span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[India: Dalits freed to testify of Jesus]]></title>
<link>http://joelnews.wordpress.com/?p=41</link>
<pubDate>Wed, 01 Oct 2008 19:33:23 +0000</pubDate>
<dc:creator>joelnews</dc:creator>
<guid>http://joelnews.fr.wordpress.com/2008/10/01/india-dalits-freed-to-testify-of-jesus/</guid>
<description><![CDATA[Gospel for Asia reports that their missionaries in India frequently have opportunities to pray for t]]></description>
<content:encoded><![CDATA[<p><span style="font-size:x-small;color:#333333;font-family:Verdana;">Gospel for Asia reports that their missionaries in India frequently have opportunities to pray for the sick. Often God mercifully brings healing, and many people choose to follow Jesus after seeing that He is far more powerful than their idols. God often builds His kingdom through a ripple effect, and many Dalit ('Untouchable') communities exemplify this as God works in powerful ways to show His love.</span></p>
]]></content:encoded>
</item>

</channel>
</rss>
