FACTOID # 104: The Pitcairn Islands have the world’s shortest highway system, with only 6.4 kilometers of road. They also have the fourth-fewest main phone lines.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

Encyclopedia > Java Native Interface

The Java Native Interface (JNI) is a programming framework that allows Java code running in the Java virtual machine (VM) 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. A software framework is a reusable design for a software system (or subsystem). ... Java is an object-oriented applications programming language developed by Sun Microsystems in the early 1990s. ... A Java Virtual Machine (JVM), originally developed by Sun Microsystems, is a virtual machine that executes Java bytecode. ... Hardware is the general term that is used to describe physical artifacts of a technology. ... An operating system (OS) is a set of computer programs that manage the hardware and software resources of a computer. ... C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ... C++ (pronounced see plus plus, IPA: ) is a general-purpose, high-level programming language with low-level facilities. ... An assembly language is a low-level language used in the writing of computer programs. ...


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. Before resorting to using the JNI developers should make sure the functionality is not already provided in the standard libraries. In object-oriented programming, a class is a programming language construct that is used to group related instance variables and methods. ... Illustration of an application which may use libvorbisfile. ...


The JNI framework lets a native method utilize Java objects in the same way that Java code uses these objects. A native method can create Java objects and then inspect and use these objects to perform its tasks. A native method can also inspect and use objects created by Java application code. In strictly mathematical branches of computer science the term object is used in a purely mathematical sense to refer to any thing. While this interpretation is useful in the discussion of abstract theory, it is not concrete enough to serve as a primitive datatype in the discussion of more concrete...


JNI is sometimes referred to as the "escape valve" for Java developers because it allows them to add functionality to their Java Application that the Java API can't provide. It can be used to interface with code written in other languages, like C++. It is also used for time-critical calculations or operations like solving complicated mathematical equations, since native code can potentially be faster than JVM code.


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

  1. as mentioned before, the JNI is not an easy API to learn;
  2. only applications and signed applets can invoke the JNI;
  3. 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);
  4. there is no garbage collection for the JNI side (JNI code must do explicit deallocation);
  5. error checking is a MUST or it has the potential to crash the JNI side and the JVM.

Contents

A Java virtual machine or JVM is a virtual machine that runs Java byte code. ...

How the JNI works

In JNI, native functions are implemented in a separate .c or .cpp file. (C++ provides a slightly cleaner interface with JNI.) When the JVM invokes the function, it passes a JNIEnv pointer, a jobject pointer, and any Java arguments declared by the Java method. A JNI function may look like this:

 JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj) { //Implement Native Method Here } 

The env pointer is a structure that contains the interface to the JVM. It includes all of the functions necessary to interact with the JVM and to work with Java objects. Example JNI functions are converting native arrays to/from Java arrays, converting native strings to/from Java strings, instantiating objects, throwing exceptions, etc. Basically, anything that Java code can do can be done using JNIEnv, albeit with considerably less ease.


For example, the following converts a Java string to a native string:

 //C++ code JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj, jstring javaString) { //Get the native string from javaString const char *nativeString = env->GetStringUTFChars(javaString, 0); //Do something with the nativeString //DON'T FORGET THIS LINE!!! env->ReleaseStringUTFChars(javaString, nativeString); } 
 //C code JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj, jstring javaString) { //Get the native string from javaString const char *nativeString = (*env)->GetStringUTFChars(env, javaString, 0); //Do something with the nativeString //DON'T FORGET THIS LINE!!! (*env)->ReleaseStringUTFChars(env, javaString, nativeString); } 

Note that C++ JNI code is cleaner than C JNI code because like Java, C++ uses object method invocation semantics. That means that in C, the env parameter is dereferenced using (*env)-> and env has to be explicitly passed to JNIEnv methods. In C++, the env parameter is dereferenced using env-> and the env parameter is implicity passed as part of the object method invocation semantics.


Native data types can be mapped to/from Java data types. For compound types such as objects, arrays and strings the native code must explicitly convert the data by calling methods in the JNIEnv. A data type is a constraint placed upon the interpretation of data in a type system in computer programming. ... This article or section does not cite its references or sources. ... In computer programming and some branches of mathematics, strings are sequences of various simple objects. ...


Mapping types

The following table shows the mapping of types between Java and native code.

Native Type Java Language Type Description Type signature
bool jboolean unsigned 8 bits Z
byte jbyte signed 8 bits B
char jchar unsigned 16 bits C
short jshort signed 16 bits S
long jint signed 32 bits I
long long jlong signed 64 bits J
float jfloat 32 bits F
double jdouble 64 bits D

In addition, the signature "L fully-qualified-class ;" would mean the class uniquely specified by that name; e.g., the signature "Ljava/lang/String;" refers to the class java.lang.String. Also, prefixing [ to the signature makes the array of that type; for example, [I means the int array type.


Here, these types are interchangeable. You can use jint where you normally use an int, and vice-versa, without any typecasting required. The word typecasting (past participle typecast) can mean more than one thing: typecasting (programming) typecasting (acting) in acting This is a disambiguation page — a navigational aid which lists other pages that might otherwise share the same title. ...


However, mapping between Java Strings and arrays to native strings and arrays is different. If you use a jstring in where a char * would be, your code could crash the JVM.

 /*********************************************** *NO!!! NO!!! NO!!! NO!!! NO!!! * ***********************************************/ JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj, jstring javaString) { printf("%s", javaString); } 
 /*********************************************** *YES!!! YES!!! YES!!! YES!!! YES!!! * ***********************************************/ JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj, jstring javaString) { //Get the native string from javaString const char *nativeString = env->GetStringUTFChars(env,javaString, 0); printf("%s", nativeString); //DON'T FORGET THIS LINE!!! env->ReleaseStringUTFChars(env,javaString, nativeString); } 

This is similar with Java arrays, as illustrated in the example below that takes the sum of all the elements in an array.

 /*********************************************** *NO!!! NO!!! NO!!! NO!!! NO!!! * ***********************************************/ JNIEXPORT jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr) { int i, sum = 0; for (i = 0; i < 10; i++) { sum += arr[i]; } return sum; } 
 /*********************************************** *YES!!! YES!!! YES!!! YES!!! YES!!! * ***********************************************/ JNIEXPORT jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr) { jint buf[10]; jint i, sum = 0; env->GetIntArrayRegion(arr, 0, 10, buf); for (i = 0; i < 10; i++) { sum += buf[i]; } return sum; } 

Of course, there is much more to it than this. Look for links below for more information.


JNIEnv*

In each native call JNIEnv argument is only valid during the call. To use the argument outside the call you need to use AttachCurrentThread and DetachCurrentThread, like so:


JNIEnv *env; (*g_vm)->AttachCurrentThread (g_vm, (void **) &env, NULL); // do stuff (*g_vm)->DetachCurrentThread (g_vm);


Native AWT painting

Not only can native code interface with Java, it can also draw on a Java Canvas, which is possible with the Java AWT Native Interface. The process is almost the same, with just a few changes. The Java AWT Native Interface is only available since J2SE 1.3. // Introduction The Java Native Interface enabled Developers to add platform-dependant functionality to Java Applications. ... Java 2 Platform, Standard Edition or J2SE is a collection of java Application Programming Interfaces targeting Java platform applications running on a workstation. ...


Microsoft's RNI

Microsoft's implementation of a Java Virtual Machine has a similar mechanism for calling native Windows code from Java, called the Raw Native Interface (RNI).


See also

// Introduction The Java Native Interface enabled Developers to add platform-dependant functionality to Java Applications. ... GlueGen is a Java tool which automatically generates the Java and JNI code necessary to call C libraries from Java code. ... Platform Invocation Services, commonly referred to as just P/Invoke, is a feature of Common Language Infrastructure implementations, like Microsofts Common Language Runtime, that enables managed code to call native code in dynamic-linked libraries (DLLs). ... The Microsoft . ... SWIG (Simplified Wrapper and Interface Generator) is a free computer software tool used to connect programs written in C/C++ with scripting languages such as Tcl, Perl, Python, Ruby, Guile, PHP and other languages like Java, C#, and Ocaml. ...

External links


 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your location
Your comments
Please enter the 5-letter protection code


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms.