Java Native Interface (JNI)

  • Support native course
    • Non-Java codes
  • JNI is like a bridge between the byte code running in JVM and native code.
  • Component needed for JNI application
    • Java code
    • Native code
    • JNI header file
    • C/C++ compiler
  • In your C/C++ file we must include JNI export and JNICAL libraries.
  • JNI compiles our code into native languages.
  • JNI helps us to write low level code that allows access to hardware directly.
  • Weekend reuse legacy code of product.
  • Creates an interface between the legacy code and Java so that you can build upon it.
  • The native keyword before a method indicates that implementation will be provided by a native code.
  • This keyword transforms our method into an abstract method.
  • We can use static or shared library while creating a native implementation program.
    • In static libraries all the code is included in our executable file, leading to an increase of its size.
    • In shared library The code used is only referenced, hence the executable needs to run in an environment that has access to all the files needed.
  • Our C/C++ code will be like
    • JNIEXPORT Void JNICALL java_com_jniapplication_JniMainApp_hello (JNIEnv*,Jobject,jstring) {
    • Std::count<<“Hello”<<name<<std::endl;
    • }
  • JNIEXPORT includes a method in the function table allowing JNI to find it.
    • This table contains pointers in the memory to the implementation of all our native methods to help us call them from our Java code.
  • JNICALL ensures that our methods are available and ready to be used by the JNI framework.
  • Arguments passed are (JNIEnv*,Jobject,jstring)
    • The environment pointer (JNIENV) is passed as an argument for each native function mapped to a Java Method, it allows us to interact with the JNI Environment within the native method.
    • jobject is instance of our JniMainaApp class.
    • Jstring is actual parameter used by our hello method.
  • Disadvantages
    • Function calls to JNI methods are expensive.
    • You will lose platform portability which is the main advantage of using Java.
    • Add an external layer of communication between the cord running in the JVM and our native code.
  • Source Code at javacodes/jniapplication at master · gauravmatta/javacodes (github.com)

No comments:

Post a Comment