环境:Windows 11 + OpenJDK21 + IDEA + VS2022

调用C++的add(int a, int b) return a+b;方法流程

IDEA创建项目

创建demo项目

编写add.java代码

public class add {
    native public static int add(int a, int b);
}

生成jni.h文件

javac -encoding utf8 -h . add.java

将org_example_add.h导入到VS2022生成的C++动态链接库项目中

VS2022创建DLL项目

创建动态链接库

配置JNI开发环境:以Debug-X64为基础编译配置

在【项目属性】 -> 【VC++目录】 -> 【包含目录】中,添加JNI头文件的路径:%JAVA_HOME%\include;%JAVA_HOME%\include\win32

编辑代码

将java生成的jni.h文件(org_example_add.h)放入DLL项目中
#pragma once
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for cl替换ass org_example_add */
#ifndef ORG_EXAMPLE_ADD_H
#define ORG_EXAMPLE_ADD_H

#include <jni.h>

#endif // ORG_EXAMPLE_ADD_H
#ifndef _Included_org_example_add
#define _Included_org_example_add
#ifdef __cplusplus
extern "C" {
#endif
	/*
	 * Class:     org_example_add
	 * Method:    add
	 * Signature: (II)I
	 */
	JNIEXPORT jint JNICALL Java_org_example_add_add
	(JNIEnv*, jclass, jint, jint);

#ifdef __cplusplus
}
#endif
#endif
编写实现代码(dllmain.cpp)
#include <jni.h>
#include "pch.h"
#include "org_example_add.h"

JNIEXPORT jint JNICALL Java_org_example_add_add(JNIEnv* env, jclass cls, jint a, jint b) {
    return a + b;
}

编译生成dll文件

实现Java调用C++动态链接库

将生成的DllDemo.dll与DllDemo.lib文件复制到Java项目src目录下

配置Java库路径

在运行配置中设置 VM options
  1. 打开运行配置:

    • 点击菜单栏 Run → Edit Configurations...

    • 点击工具栏中的运行配置下拉菜单,选择 Edit Configurations...

  2. 设置 VM 选项:

    • 在 VM options 字段中添加:-Djava.library.path=<ProjectPath-SRc>

编写调用代码

public class main {
    static{
        // 使用 System.loadLibrary 加载 DLL
        System.loadLibrary("DllDemo");
    }
    public static void main(String[] args){
        int result = add.add(5, 10);
        System.out.println("The sum is: " + result);
    }
}