JNI

一、创建java类

1
2
3
4
5
6
7
8
9
10
11
package com.hanyu.jni;

public class NativeTest {
static {
System.loadLibrary("NativeTest");
}

public static native void test();

public static native String testReturn(String str);
}

二、生成C++头文件

Idea配置javah

Setting -> Tools -> External Tools

Name: javah
Program: $JDKPath$\bin\javah
Arguments: -encoding UTF-8 -classpath $FileRelativeDir$/../../../ $FileClass$
Working Directory: $ProjectFileDir$

配置完成后,右键java类 External Tools -> javah

javah命令

无包名
javah -encoding UTF-8 XXX

有包名,在com包上级目录下执行
javah -encoding UTF-8 com.xxx.xxx.XXX

生成后的文件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_hanyu_jni_NativeTest */

#ifndef _Included_com_hanyu_jni_NativeTest
#define _Included_com_hanyu_jni_NativeTest
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_hanyu_jni_NativeTest
* Method: test
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_hanyu_jni_NativeTest_test
(JNIEnv *, jclass);

/*
* Class: com_hanyu_jni_NativeTest
* Method: test
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_hanyu_jni_NativeTest_test
(JNIEnv *, jclass, jstring);

#ifdef __cplusplus
}
#endif
#endif

jni.h文件在%JAVA_HOME%/include目录下

三、引入.h文件,编写c代码

安装gcc

github在线安装包
github离线安装包
离线镜像站点
安装完成后查看gcc版本gcc -v

编写C代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "com_hanyu_jni_NativeTest.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

JNIEXPORT void JNICALL Java_com_hanyu_jni_NativeTest_test(JNIEnv *env, jobject obj)
{
printf("test JNI");
}

JNIEXPORT jstring JNICALL Java_com_hanyu_jni_NativeTest_test(JNIEnv *env, jobject obj, jstring str)
{
printf(">>> %s <<<", str);
// 生成一个随机数并返回
srand((unsigned int)time(NULL));
int r = rand();
char str1[10];
sprintf(str1, "%d", r);
return (*env)->NewStringUTF(env, str1);
}

四、生成dll库

在文件NativeTest.c目录下,执行cmd
gcc -m64 -Wl,--add-stdcall-alias -I"F:\Java\jdk1.8.0_211\include" -I"F:\Java\jdk1.8.0_211\include\win32" -shared -o NativeTest.dll NativeTest.c
-m64:64位dll库文件
-shared:编译为dll


JNI
https://touchhanyu.cn/2024/03/19/code/java/jni/
作者
皮蛋瘦肉粥
发布于
2024年3月19日
许可协议