java_native_interface_jni

Java Native Interface (JNI)

Overview

Java Native Interface (JNI) is a framework that enables Java code running in the Java Virtual Machine (JVM) to interact with applications and libraries written in other languages, primarily C, C++, and assembly. JNI allows Java code to call native methods and vice versa, facilitating interoperability between Java and native code.

Key Features

  • **Calling Native Methods:** Java code can invoke functions implemented in native libraries using JNI. This allows Java to access platform-specific features or leverage existing native code.
  • **Embedding JVM:** Native applications can embed the JVM, allowing them to execute Java code and access Java libraries.
  • **Data Exchange:** JNI provides mechanisms for exchanging data between Java and native code, including primitive types, objects, arrays, and strings.
  • **Exception Handling:** JNI allows exceptions thrown in Java code to be caught and handled in native code, and vice versa.
  • **Reflection:** JNI provides limited reflection capabilities, allowing native code to inspect and manipulate Java classes and objects.

Resources

Code Example

**Java (Calling Native Method):**

```java public class Example {

   // Declare a native method
   private native void sayHello();
   static {
       // Load the native library
       System.loadLibrary("example");
   }
   public static void main(String[] args) {
       new Example().sayHello();
   }
} ```

**C (Implementing Native Method):**

```c

  1. include <jni.h>
  2. include <stdio.h>

JNIEXPORT void JNICALL Java_Example_sayHello(JNIEnv *env, jobject obj) {

   printf("Hello from C!\n");
} ```

In this example, the Java code declares a native method `sayHello` and loads a native library named `example`. The C code implements this method, which simply prints a message to the console.

java_native_interface_jni.txt · Last modified: 2024/08/12 05:26 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki