Java 生成 JNI 头文件

2020-06-19  本文已影响0人  Nothing_655f

介绍两个生成jni头文件的方法,一般是用函数签名类型来做native 实现

1. 使用 javac 生成 JNI 头文件

1.1 基本使用方法

1. JDK版本必须在 1.8 以上

2. 执行命令 javac -encoding utf8 -h targetDir sourceFile

1.2 示例

切换到文件所在目录打开命令行

执行命令

javac -encoding utf8 -h . DemoCpp.java

(注意 点 后面有个空格,点表示当前路径)
-encoding utf8 指定源文件编码格式
-h . 头文件的输出目录,. 表示当前目录,后面必需加个空格
DemoCpp.java 源文件

2. 生成的头文件内容

DemoCpp.h

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

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     DemoCpp
 * Method:    HelloWord
 * Signature: (Ljava/lang/String;II)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL DemoCpp_HelloWord
  (JNIEnv *, jobject, jstring, jint, jint);
#ifdef __cplusplus
}
#endif
#endif

2. 使用 javah 生成 JNI 头文件

2.1 基本使用方法

在包结构开始的目录打开命令行窗口;

执行命令:javah -d targetDir -classpath . 包路径+类名(类名不包含文件后缀名)

2.1.1 在包结构开始的目录打开命令行窗口

在源代码包结构开始处或者class文件包结构开始处都可以;

2.1.2 执行命令:

javah -classpath . com.xxx.xxx.xxx.jni.NativeCpp

-classpath . 指定加载类的路径,因为当前目录是包结构开始的目录,所以使用 . ,表示当前目录;

com.xxx.xxx.xxx.jni.NativeCpp 本地方法所在的包路径+类名(注意没有.java或者.class的后缀);

2.1.3 结果

不指定输出路径,生成的头文件默认在当前目录下;

使用 -d targetDir 指定输出路径,

javah -d ../ -classpath . Java_com_xxx_xxx_xxx_jni_NativeCpp
此处指定头文件生成在当前目录的父目录

2.1.4 头文件内容

/* DO NOT EDIT THIS FILE - it is machine generated */ 
#include <jni.h>
/* Header for class Java_com_xxx_xxx_xxx_jni_NativeCpp*/
#ifdef __cplusplus 
extern "C" { 
#endif
/* * Class:     Java_com_xxx_xxx_xxx_jni_NativeCpp
 * Method:    parseBlacBox
 * Signature: (Ljava/lang/String;II)Ljava/lang/String; 
*/ 
JNIEXPORT jstring JNICALL Java_com_xxx_xxx_xxx_jni_NativeCpp_parseBlacBox
  (JNIEnv *, jobject, jstring, jint, jint);

#ifdef __cplusplus
} #endif
#endif
上一篇 下一篇

猜你喜欢

热点阅读