1. JNI overview

JNI is short for Java Native Interface

  • Java is a cross-platform programming language, but there are still times when it is necessary to call native code (often written in C and C++).
  • JNI is a powerful interface to the Java platform. This JNI interface provides the function of calling between Java and the native code of the operating system.

2. Steps of C/C++ code

  • Declare a native method in a Java class
public native void sayHello();
  • Use the javah command to generate C/C++ header files containing native method declarations
javah com.omg.NativeLib
  • Use the generated C/C++ header files to write C/C++ source files
#include<iostream>
#include "com_omg_NativeLib.h"
using namespace std;

JNIEXPORT void JNICALL Java_com_olive_NativeLib_sayHello (JNIEnv *, jobject){
    cout << "hello world" << endl;
}
  • Compile C/C++ source files into dynamic link libraries (DLL for windows, so for Linux)
  • Add the path of the dll file to the environment variable PATH
  • Load the dll file in the Java class and then call the declared native method
System.load("C:\\lib\\NativeCodeJni.dll");
NativeLib nl = new NativeLib();
nl.sayHello();

或者

System.loadLibrary("NativeCodeJni");
NativeLib nl = new NativeLib();
nl.sayHello();

3. Disadvantages of using JNI

  • Using JNI, then this Java Application will not be cross-platform. If you need to port to other platforms, you need to rewrite the native code
  • Java is a strongly typed language, C/C++ is not. So be more careful when writing JNI
  • In short, you must use as little native code as possible when building Java programs

Visual studio environment configuration


BUG弄潮儿
101 声望15 粉丝