亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
? How JNI Works: The Big Picture
?? Step-by-Step Example: Calling C from Java
1. Write the Java Class
2. Generate Header File Using javah (Deprecated) or javac -h
3. Implement the Native Method in C
4. Compile the C Code into a Shared Library
On Linux/macOS:
On Windows (using MinGW or MSVC):
5. Run the Program
? Passing and Returning Data Types
Example: Add Two Integers in C
? Accessing Java Fields and Methods from Native Code
?? Common Pitfalls & Best Practices
? When Should You Use JNI?
Summary
Home Java javaTutorial Java Native Interface (JNI) Explained with Examples

Java Native Interface (JNI) Explained with Examples

Jul 28, 2025 am 12:20 AM
java jni

JNI allows Java code to interact with local code written in C/C and other languages, and implement it as a shared library by declaring native methods, generating header files, writing and compiling C as a shared library, loading the library and running the program to achieve calls; 2. Data is converted between Java and local types through JNI functions, such as jstring and char*; 3. Local code can call back Java methods, and you need to obtain class references, method IDs and use functions such as CallVoidMethod; 4. Pay attention to naming specifications, exception checking, memory management, thread safety and performance overhead when using them; 5. It is suitable for accessing system resources, reusing native libraries or improving performance, but it should be avoided when pure Java can solve or emphasize portability; JNI is a powerful but cautious tool, and correct application can significantly expand Java capabilities.

Java Native Interface (JNI) Explained with Examples

Java Native Interface (JNI) allows Java code running in the Java Virtual Machine (JVM) to interact with native applications and libraries written in other languages such as C, C , or assembly. This is useful when you need to access system-level resources, leverage existing native code, or improve performance for computationally intense tasks.

Java Native Interface (JNI) Explained with Examples

While Java is designed to be platform-independent, JNI introduces platform-specific dependencies — but it gives you powerful low-level control when needed.

Let's break down how JNI works, step by step, with a practical example.

Java Native Interface (JNI) Explained with Examples

? How JNI Works: The Big Picture

JNI acts as a bridge between Java and native code:

  1. Java calls native methods declared with the native keyword.
  2. The JVM loads a shared library ( .dll on Windows, .so on Linux, .dylib on macOS).
  3. The native code implements those methods , typically in C/C .
  4. Data is converted between Java and native types using JNI functions.
  5. Optionally, native code can call back into Java methods .

?? Use JNI carefully — it bypasses JVM safety features like garbage collection and security checks.

Java Native Interface (JNI) Explained with Examples

?? Step-by-Step Example: Calling C from Java

We'll create a simple program where Java calls a C function that returns a string.

1. Write the Java Class

 // HelloWorld.java
public class HelloWorld {
    // Declare native method
    public native String saysHello();

    // Load native library
    static {
        System.loadLibrary("hello"); // Loads libhello.so (Linux), hello.dll (Windows), or libhello.dylib (macOS)
    }

    public static void main(String[] args) {
        HelloWorld hw = new HelloWorld();
        System.out.println(hw.sayHello());
    }
}

Compile it:

 javac HelloWorld.java

This generates HelloWorld.class .


2. Generate Header File Using javah (Deprecated) or javac -h

Since JDK 8, javah is deprecated. Use:

 javac -h . HelloWorld.java

This generates a header file: HelloWorld.h , which looks like:

 /* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif

/*
 * Class: HelloWorld
 * Method: sayHello
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_HelloWorld_sayHello
  (JNIEnv *, job);

#ifdef __cplusplus
}
#endif
#endif

Note:

  • Java_HelloWorld_sayHello is the required naming convention.
  • JNIEnv* is the interface pointer to access JNI functions.
  • jobject refer to the instance of the HelloWorld object.

3. Implement the Native Method in C

Create HelloWorld.c :

 #include <jni.h>
#include "HelloWorld.h"
#include <string.h>

JNIEXPORT jstring JNICALL Java_HelloWorld_sayHello
  (JNIEnv *env, job obj) {
    return (*env)->NewStringUTF(env, "Hello from C via JNI!");
}

Here:

  • We use (*env)->NewStringUTF() to convert a C string ( char* ) to a jstring .
  • All JNI functions are accessed through the JNIEnv pointer.

4. Compile the C Code into a Shared Library

On Linux/macOS:
 gcc -fPIC -I"${JAVA_HOME}/include" -I"${JAVA_HOME}/include/linux" \
    -shared -o libhello.so HelloWorld.c

Replace /linux with /darwin on macOS.

On Windows (using MinGW or MSVC):
 gcc -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" 
    -shared -o hello.dll HelloWorld.c

Make sure the output matches what System.loadLibrary() expects:

  • Linux: libhello.so
  • Windows: hello.dll
  • macOS: libhello.dylib

5. Run the Program

Ensure the shared library is in the library path:

 java -Djava.library.path=. HelloWorld

Output:

 Hello from C via JNI!

? Success! Java called your C function.


? Passing and Returning Data Types

JNI supports various data type conversions.

Java Type Native Type (C/C ) JNI Typedef
boolean unsigned char jboolean
byte signed char jbyte
int int jint
long long long jlong
double double jdouble
String char* (modified UTF-8) jstring
Object[] jobjectArray array of references

Example: Add Two Integers in C

Java:

 public class MathLib {
    public native int add(int a, int b);
    static {
        System.loadLibrary("math");
    }
    public static void main(String[] args) {
        MathLib ml = new MathLib();
        System.out.println("5 7 = " ml.add(5, 7));
    }
}

C implementation ( MathLib.c ):

 #include <jni.h>
#include "MathLib.h"

JNIEXPORT jint JNICALL Java_MathLib_add
  (JNIEnv *env, job obj, jint a, jint b) {
    return ab;
}

Same compilation steps apply.


? Accessing Java Fields and Methods from Native Code

Native code can also call back into Java .

Example: Call a Java method from C.

Java:

 public class CallbackExample {
    private int value = 42;

    public void printValue() {
        System.out.println("Value from Java: " value);
    }

    public native void callPrintValue();

    static {
        System.loadLibrary("callback");
    }

    public static void main(String[] args) {
        new CallbackExample().callPrintValue();
    }
}

C implementation:

 #include <jni.h>
#include "CallbackExample.h"

JNIEXPORT void JNICALL Java_CallbackExample_callPrintValue
  (JNIEnv *env, job obj) {

    // Get the class
    jclass cls = (*env)->GetObjectClass(env, obj);

    // Find the method ID
    jmethodID mid = (*env)->GetMethodID(env, cls, "printValue", "()V");
    if (mid == NULL) return; // method not found

    // Call the Java method
    (*env)->CallVoidMethod(env, obj, mid);
}

Signature "()V" means: no arguments, returns void.

Recompile and run → Output:

 Value from Java: 42

You've just made C call a Java method!


?? Common Pitfalls & Best Practices

  • Naming Convention : Native method names must follow Java_PackageName_ClassName_MethodName .
  • Exception Handling : Always check for exceptions after critical JNI calls using (*env)->ExceptionCheck() or ExceptionOccurred() .
  • Memory Management : Local references created in native code are automatically cleaned up unless pinned. Avoid memory leaks.
  • Thread Safety : JNIEnv is thread-local. Don't share it across threads.
  • Performance : Crossing the JNI boundary has overhead. Minimize frequently calls.
  • Portability : Native libraries are OS/architecture-specific. You may need multiple builds.

? When Should You Use JNI?

Use JNI when:

  • Interfacing with hardware or OS APIs (eg, device drivers).
  • Reusing legacy C/C codebases.
  • Performance-critical sections (eg, math, image processing).
  • Integrating with native libraries (OpenCV, OpenSSL, etc.).

Avoid JNI when:

  • Pure Java solutions exist.
  • Portability is key.
  • Simplicity and maintenanceability matter more than speed.

Summary

JNI enables powerful integration between Java and native code. With just a few steps — declare native methods, generate headers, write C code, compile to shared library, and load it — you can extend Java's capabilities beyond the JVM.

It's not something you use every day, but when you need it, it's indispensable.

Basically, JNI opens the door — just be careful what you bring through.

The above is the detailed content of Java Native Interface (JNI) Explained with Examples. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A Developer's Guide to Maven for Java Project Management A Developer's Guide to Maven for Java Project Management Jul 30, 2025 am 02:41 AM

Maven is a standard tool for Java project management and construction. The answer lies in the fact that it uses pom.xml to standardize project structure, dependency management, construction lifecycle automation and plug-in extensions; 1. Use pom.xml to define groupId, artifactId, version and dependencies; 2. Master core commands such as mvnclean, compile, test, package, install and deploy; 3. Use dependencyManagement and exclusions to manage dependency versions and conflicts; 4. Organize large applications through multi-module project structure and are managed uniformly by the parent POM; 5.

Building RESTful APIs in Java with Jakarta EE Building RESTful APIs in Java with Jakarta EE Jul 30, 2025 am 03:05 AM

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

Developing a Blockchain Application in Java Developing a Blockchain Application in Java Jul 30, 2025 am 12:43 AM

Understand the core components of blockchain, including blocks, hashs, chain structures, consensus mechanisms and immutability; 2. Create a Block class that contains data, timestamps, previous hash and Nonce, and implement SHA-256 hash calculation and proof of work mining; 3. Build a Blockchain class to manage block lists, initialize the Genesis block, add new blocks and verify the integrity of the chain; 4. Write the main test blockchain, add transaction data blocks in turn and output chain status; 5. Optional enhancement functions include transaction support, P2P network, digital signature, RESTAPI and data persistence; 6. You can use Java blockchain libraries such as HyperledgerFabric, Web3J or Corda for production-level opening

python property decorator example python property decorator example Jul 30, 2025 am 02:17 AM

@property decorator is used to convert methods into properties to implement the reading, setting and deletion control of properties. 1. Basic usage: define read-only attributes through @property, such as area calculated based on radius and accessed directly; 2. Advanced usage: use @name.setter and @name.deleter to implement attribute assignment verification and deletion operations; 3. Practical application: perform data verification in setters, such as BankAccount to ensure that the balance is not negative; 4. Naming specification: internal variables are prefixed, property method names are consistent with attributes, and unified access control is used to improve code security and maintainability.

css dark mode toggle example css dark mode toggle example Jul 30, 2025 am 05:28 AM

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

css dropdown menu example css dropdown menu example Jul 30, 2025 am 05:36 AM

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

How to use Java MessageDigest for hashing (MD5, SHA-256)? How to use Java MessageDigest for hashing (MD5, SHA-256)? Jul 30, 2025 am 02:58 AM

To generate hash values using Java, it can be implemented through the MessageDigest class. 1. Get an instance of the specified algorithm, such as MD5 or SHA-256; 2. Call the .update() method to pass in the data to be encrypted; 3. Call the .digest() method to obtain a hash byte array; 4. Convert the byte array into a hexadecimal string for reading; for inputs such as large files, read in chunks and call .update() multiple times; it is recommended to use SHA-256 instead of MD5 or SHA-1 to ensure security.

python parse date string example python parse date string example Jul 30, 2025 am 03:32 AM

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d

See all articles