当前位置:网站首页>JNI函数的2种书写方式
JNI函数的2种书写方式
2022-06-28 11:39:00 【一杯苦芥】
一、静态注册
- 原理:
- 根据函数名来建立 java 方法与 JNI 函数的一一对应关系;
- 以Java为前缀,并且用“_”下划线,将包名、类名以及native方法名连接起来;
- 实现流程:
- 编写 java 代码;
- 利用 javah 指令生成对应的 c 文件;
- 对 c 文件中的声明进行实现;
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
二、动态注册
- 原理:
- 利用 RegisterNatives 方法来注册 java 方法与 JNI 函数的一一对应关系;
- 实现流程:
- 利用结构体 JNINativeMethod 数组记录 java 方法与 JNI 函数的对应关系;
- 实现 JNI_OnLoad 方法,在加载动态库后,执行动态注册;
- 调用 FindClass 方法,获取 java 对象;
- 调用 RegisterNatives 方法,传入 java 对象,以及 JNINativeMethod 数组,以及注册数目完成注册;
public class JniUtils {
static {
System.loadLibrary("native-lib");
}
public static native String stringFromJNI();
public static native int calculateByJNI(int count);
}
#include <jni.h>
#include <string>
// 指定要注册的类
#define JNIREG_CLASS "com/example/jnilibrary/JniUtils"
// 指定代码所在的段。在编译时,把该函数编译到自定义的section里。
// 由于在java层没有定义该函数,因此需要写到一个自定义的section里。
extern "C"
__attribute__((section(".mysection"))) JNICALL jstring getStr1(JNIEnv *env, jobject obj) {
return env->NewStringUTF("Hello from C++");
}
extern "C"
__attribute__((section(".mysection"))) JNICALL jint getInt1(JNIEnv *env, jobject obj, jint count) {
return (count + 1);
}
// 第一个参数:Java层的方法名
// 第二个参数:方法的签名,括号内为参数类型,后面为返回类型
// 第三个参数:需要重新注册的方法名
static JNINativeMethod getMethods[] = {
{"stringFromJNI", "()Ljava/lang/String;", (void *) getStr1},
{"calculateByJNI", "(I)I", (void *) getInt1}
};
extern "C"
int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *getMethods,
int numMethods) {
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, getMethods, numMethods) < 0) {
return JNI_FALSE;
}
return JNI_TRUE;
}
extern "C"
int registerNatives(JNIEnv *env) {
if (!registerNativeMethods(env, JNIREG_CLASS, getMethods,
sizeof(getMethods) / sizeof(getMethods[0]))) {
return JNI_FALSE;
}
return JNI_TRUE;
}
extern "C"
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env;
if (vm->GetEnv((void **) (&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
if (!registerNatives(env)) {
return -1;
}
return JNI_VERSION_1_6;
}边栏推荐
- [sciter]: how sciter uses i18 to realize multi language switching of desktop applications and its advantages and disadvantages
- .NET混合开发解决方案24 WebView2对比CefSharp的超强优势
- IO stream of file and Base64
- Dongyuhui, New Oriental and Phoenix Satellite TV
- Fruit FL studio/cubase/studio one music host software comparison
- Simulation of the Saier lottery to seek expectation
- AcWing 610. Salary and bonus (implemented in C language)
- day23 js笔记 2021.09.14
- 开源项目维权成功案例: spug 开源运维平台成功维权
- Prefix and (one dimension)
猜你喜欢

赛尔号抽奖模拟求期望

【C语言】NextDay问题

Tidb v6.0.0 (DMR): initial test of cache table - tidb Book rush

js中的数组方法 2021.09.18

Web3安全连载(3) | 深入揭秘NFT钓鱼流程及防范技巧

Join hands with cigent: group alliance introduces advanced network security protection features for SSD master firmware

day34 js笔记 正则表达式 2021.09.29

Array method in JS 2021.09.18

【C语言】关于scanf()与scanf_s()的一些问题

Many benefits of SEO optimization are directly related to traffic
随机推荐
[sciter]: how sciter uses i18 to realize multi language switching of desktop applications and its advantages and disadvantages
Necessary for beginners PR 2021 quick start tutorial, PR green screen matting operation method
Redis principle - List
Remote login sshd service
Connectionreseterror: [winerror 10054] the remote host forced an existing connection to be closed
2. single digit statistics
AcWing 607. Average 2 (implemented in C language)
Day34 JS notes regular expression 2021.09.29
Random forest and poetry maker trained by AMR
Batch will png . bmp . JPEG format pictures are converted to Jpg format picture
建立自己的网站(18)
day31 js笔记 DOM下 2021.09.26
Packaging and publishing application of jetpack compose desktop version
The development and principle of the metacosmic system
Day29 JS notes 2021.09.23
fatal: unsafe repository (‘/home/anji/gopath/src/gateway‘ is owned by someone else)
[Beijing University of Aeronautics and Astronautics] information sharing for the first and second examinations of postgraduate entrance examination
day33 js笔记 事件(下)2021.09.28
Int~long long indicates the maximum and minimum number
Still using simpledateformat for time formatting? Be careful that the project collapses!