[Transfer] native method in Java

foreword

While studying the book "In-depth Understanding of Java Virtual Machine", I saw the concept of native method stack (Native Method Stack) in the runtime data area of ​​Java virtual machine. The method is not implemented by the Java language, it can be implemented by C/C++, and then called through JNI (Java Native Interface). Of course, there is also a Java virtual machine stack, which serves Java methods. This article is mainly to familiarize yourself with how to call the Native method.

Call C++ method through JNI

  • Calling C++ methods through java code

import java.io.File;

public class Main {

    static {
        System.load("E:" + File.separator + "test.dll");
    }

    public native static void TestOne();
    public static void main(String[] args) {
        TestOne();
    }
}
  • Generate the Main.class file by javac Main.javacompiling, and then execute it javah Mainto generate the Main.h file, the purpose is to generate the .h file for the Native method in the specified class

  • Create a C++ project test through visual studio 2022. The name of the generated dll needs to be consistent with the name of the class library loaded in the above Java code

 

  • Copy the Main.h generated above, as well as %JAVA_HOME/include/jni.h% and %JAVA_HOME/include/win32/jni_md.h%, three files to the test directory, as shown in the figure:

     

  • Add the above three files to the header file

 

  • #include <jni.h>Modify the change in Main.h to#include "jni.h"

  • Add the C++ source file Hello.cpp and add the following content

#include "pch.h"
#include <iostream>
#include "Main.h"
using namespace std;

JNIEXPORT void JNICALL Java_Main_TestOne
(JNIEnv*, jclass)
{
  cout << "hello sherman" << endl;
}
  • Build the project, copy test.dll, to E:\ (I am 64-bit here)

  • Run the java program directly to see the output: "hello sherman"

Author: sherman168
Link: https://www.jianshu.com/p/21f7ebb9e63f
Source: Jianshu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

Guess you like

Origin blog.csdn.net/mao_mao37/article/details/129880058