Java(11) calls C/C++ dynamic link library Demo through JNI

Mainly refer to this article: Original link


1. Software environment

Hardware: Raspberry Pi CM4
Operating System: Official 64-bit
Compiler: g++
JDK: 11

Two, the process

  1. The class method with native modification is declared in the java code. The native method is only declared in java without implementation. Before calling the navtive method, perform system.loadLibrary("xxx"), and then call the method xxx through the class. Can
  2. Use javah to generate header files corresponding to native functions from java class files
  3. By referring to the header file containing the native method declaration, use C++ to write the implementation of the native method, and compile it into a dynamic link library
  4. Just compile and execute java
  5. It is said that jdk8 and before use javah, and later use javac -h

Three, the java part

1. Write java code in the linux directory
nano /home/hellozous/c/com/zouston/TestJNI.java
package com.zouston;

/**
 * 描述:测试JNI
 * 日期: 2022-07-06
 * 时间: 14:11
 *
 * @author: K.L.Zous
 */
public class TestJNI
{
    
    
    /**
     * 声明本地库中的函数
     */
    public native void helloWorld();

    public static void main(String[] args)
    {
    
    
        //载入本地库
        System.loadLibrary("TestJNI");
        TestJNI t = new TestJNI();
        //调用本地库中的函数
        t.helloWorld();
    }
}
2. Generate header files
javac -h ./ /home/hellozous/c/com/zouston/TestJNI.java

At this time, com_zouston_TestJNI.h is generated
, which contains the following content, as the method name in C++

JNIEXPORT void JNICALL Java_com_zouston_TestJNI_helloWorld

3. C++ part

1. Create a CPP file
nano /home/hellozous/c/com/zouston/helloWorld.cpp
#include "com_zouston_TestJNI.h"
#include <iostream>

JNIEXPORT void JNICALL Java_com_zouston_TestJNI_helloWorld(JNIEnv *env, jobject obj)
{
    
    
    std::cout << "Hello world!" << std::endl;
}
2. Generate so
g++ -fPIC -shared -o libTestJNI.so -I /usr/lib/jvm/java-11-openjdk-arm64/include -I /usr/lib/jvm/java-11-openjdk-arm64/include/linux/ helloWorld.cpp
  • The -fPIC option enables the compiler to generate position-independent code during the compilation phase, so that the shared library can be correctly loaded in memory, and PIC is Position, Independent Code. This option must be available when using the -shared option, otherwise an error will occur during compilation
  • The -shared compiler generates a shared link library
  • The naming rules of the dynamic link library after -o must be consistent with the dynamic link library under linux, that is, the form of libxxx.so
  • -I is followed by the header file path required by jni
3. Run
cd /home/hellozous/c
java -Djava.library.path=. com.zouston.TestJNI

insert image description here

Guess you like

Origin blog.csdn.net/u014492512/article/details/125639423