根据.h头文件中的方法声明,在 C/C++ 源文件中实现对应的函数

1、定义native函数:

public class MathUtils {
    public native int add(int a, int b);
    public native int subtract(int a, int b);

    static {
        System.loadLibrary("MathUtils");
    }
}

2、生成头文件:

使用 javah 命令生成对应的 C 头文件 com_example_MathUtils.h

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

#ifndef _Included_com_example_MathUtils
#define _Included_com_example_MathUtils
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_example_MathUtils
 * Method:    add
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_com_example_MathUtils_add
  (JNIEnv *, jobject, jint, jint);

/*
 * Class:     com_example_MathUtils
 * Method:    subtract
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_com_example_MathUtils_subtract
  (JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif

3、在 C++ 源文件 MathUtils.cpp 中实现这两个方法:

注意:

  • 引入头文件;
  • 函数的命名和参数类型需要与头文件中的声明一致
#include "com_example_MathUtils.h"

JNIEXPORT jint JNICALL Java_com_example_MathUtils_add
  (JNIEnv* env, jobject obj, jint a, jint b) {
    return a + b;
}

JNIEXPORT jint JNICALL Java_com_example_MathUtils_subtract
  (JNIEnv* env, jobject obj, jint a, jint b) {
    return a - b;
}

方法解释:

  • 函数声明使用 extern “C” 包裹,确保使用 C 语言的函数名修饰规则。
  • 参数类型和返回值类型使用 JNI 定义的 C++ 类型,如 jint 对应 int。
  • JNIEnv* 参数用于与 Java 端进行交互。
  • jobject 参数是调用该 native 方法的 Java 对象实例。

4、编译、使用:

编译这个 C++ 源文件,生成动态链接库文件 libMathUtils.so(或 .dll)。
最后在 Java 端加载这个动态库并调用 native 方法:

public class Main {
    public static void main(String[] args) {
        System.loadLibrary("MathUtils");
        MathUtils utils = new MathUtils();
        int result = utils.add(2, 3);
        System.out.println("2 + 3 = " + result); // Output: 2 + 3 = 5
        result = utils.subtract(10, 4);
        System.out.println("10 - 4 = " + result); // Output: 10 - 4 = 6
    }
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 10:44:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 10:44:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 10:44:02       58 阅读
  4. Python语言-面向对象

    2024-07-12 10:44:02       69 阅读

热门阅读

  1. linux 查看 io使用率iotop

    2024-07-12 10:44:02       24 阅读
  2. 【番外】Springboot集成推荐配置及十问RocketMQ

    2024-07-12 10:44:02       28 阅读
  3. 软设之职责链模式

    2024-07-12 10:44:02       20 阅读
  4. vue中ref()与reactive(的区别)

    2024-07-12 10:44:02       20 阅读
  5. Flask发布一个及时止损(止盈)服务(二)

    2024-07-12 10:44:02       21 阅读
  6. NoSQL之Redis数据库配置与优化

    2024-07-12 10:44:02       28 阅读
  7. ELK优化

    2024-07-12 10:44:02       29 阅读