环境:MacOS + OpenJDK21 + IDEA + Clion 使用 JNI简单实现 Java 调用 C++动态链接库

IDEA创建项目

创建 Java 项目

生成 jni.h 文件

命令:javac -encoding utf8 -h . add.java

Clion创建C++库项目

导入org_example_add.h 文件

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_example_add */

#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

编辑 CMakeLists.txt 文件

cmake_minimum_required(VERSION 3.31)
project(DLLDemo)

set(CMAKE_CXX_STANDARD 20)

find_package(JNI REQUIRED)
include_directories(${JNI_INCLUDE_DIRS})

add_library(DLLDemo SHARED library.cpp
        org_example_add.h)

编辑 library.cpp 文件

#include "library.h"
#include "org_example_add.h"
#include <jni.h>
#include <iostream>

JNIEXPORT jint JNICALL Java_org_example_add_add(JNIEnv *env, jclass cls, jint a, jint b) {
    std::cout << "Adding " << a << " and " << b << std::endl;
    return a + b;
}

编译并导出libDLLDemo.dylib

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

导入libDLLDemo.dylib文件到Java 项目的SRC目录下

配置Java库路径

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

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

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

  2. 设置 VM 选项:

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

编写调用

public class Main {
    static{
        // 在Unix/Linux/macOS系统上,加载库时不需要包含lib前缀
        System.loadLibrary("DLLDemo");
    }
    public static void main(String[] args) {
        int result = add.add(3, 5);
        System.out.println("sum = " + result);
    }
}