Académique Documents
Professionnel Documents
Culture Documents
Interface (JNI)
Santhosh Vasudevan
Java Native Interface (JNI)
JNI allows Java code that runs within a Java Virtual Machine (VM) to
operate with applications and libraries written in other languages,
such as C, C++, and assembly.
• Sample (output)
#include <jni.h>
…
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL
Java_<Fully_qualified_class_name>_<method_name
> (JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Steps to achieve java native interfacing
• Method Signature
e.g.,
JNIEXPORT void JNICALL Java_ calypsox_tk_core_JNInterface
getValueFromNative(JNIEnv *, jobject);
Steps to achieve java native interfacing
• Sample code
#include <jni.h>
#include “<generated>.h“
#include <some.h>
JNIEXPORT void JNICALL
Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject
obj) {
//…call any function (probably something defined in the
included *.h file – “some.h”)
return;}
Steps to achieve java native interfacing
The setup is ready to execute the native method from the Java
program after loading the above library (DLL).
Some consideration of data types
Wrong
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];
}
...
Correct
JNIEXPORT jint JNICALL
Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray
arr)
{
int i, sum = 0;
jsize len = (*env)->GetArrayLength(env, arr);
jint *body = (*env)->GetIntArrayElements(env, arr, 0);
for (i=0; i<len; i++) {
sum += body[i];
}…
Thank You