Table of Contents

Java Native Interface (JNI)

Return to Java, Foreign Function Interface (FFI)

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

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.