Due to the needs of the project, I have recently studied the method of Java calling DLL. How to call it is written here for easy reference in the future:
The approach is JNI: Java Native Interface, or JNI, a part of the Java platform that allows Java to interact with code written in other languages.
Here is a working diagram of JNI taken from the Internet:
Create a class in JAVA, use Javac to generate.class, and then generate.h by Javah; And then I copy.h to VC, and VC implements the function,
And after the compilation through the generation of DLL, DLL into the JAVA project to use, end.
Here are the specific steps (including examples) :
1, build Java class: load DLL, declare to use DLL method, the specific implementation is responsible for DLL; The code is as follows:
public class Java2cpp { static { System.loadLibrary(“javaCallcpp”); } public native int DLL_ADD(int a,int b); // add public native int DLL_SUB(int a,int b); // subtract public native int DLL_MUL(int a,int b); Public native int DLL_DIV(int a,int b); Public static void main(String args[]) {public static void main(String args[]) {
int sum = 0; Java2cpp test = new Java2cpp(); sum = test.DLL_ADD(2, 4); System.out.println(“Java call cpp dll result:” + sum); }
}
H file: go to the java2cpp. Java directory and do the following:
Javac java2cpp.java generates java2cpp.class
Java2cpp generates the java2cpp.h header file with the following contents:
Note: The contents of the java2cpp.h header file cannot be modified, otherwise an error will occur.
3, VC dynamic library: create aC /C++ dynamic library project named javaCallcpp, import java2cpp.h and implement its method:
#include “Java2cpp.h”
#include “dllApi.h”
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1ADD(JNIEnv *env, jobject obj, jint a, jint b)
{
int var = 0;
var = DLL_API_ADD(a,b);
return var; }
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1SUB(JNIEnv *env, jobject obj, jint a, jint b)
{
int var = 0;
var = DLL_API_SUB(a,b);
return var; }
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1MUL(JNIEnv *env, jobject obj, jint a, jint b)
{
int var = 0;
var = DLL_API_MUL(a,b);
return var; }
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1DIV(JNIEnv *env, jobject obj, jint a, jint b)
{
int var = 0;
var = DLL_API_DIV(a,b);
return var; }// This file is complete
Add DLL_API_ADD(), subtract DLL_API_SUB(), multiply DLL_API_MUL(), and divide DLL_API_DIV()
The file name is dllapi.cpp and the implementation is as follows:
int DLL_API_ADD(int a,int b)
{
return (a+b);
}
int DLL_API_SUB(int a,int b)
{
return (a-b);
}
int DLL_API_MUL(int a,int b)
{
return (a*b);
}
int DLL_API_DIV(int a,int b) { return (a/b); }// This file is complete
Include <jni.h> = include<jni. H > = include<jni. H > = include<jni.
Create javacallpcp. DLL and copy the DLL to the Java project directory:
5, using DLL: Run the Java program, the result is as follows:
At this point, the Java invocation DLL is complete.