当前位置:网站首页>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;
}边栏推荐
- day28 严格模式、字符串 js 2021.09.22
- Batch will png . bmp . JPEG format pictures are converted to Jpg format picture
- AcWing 608. Poor (implemented in C language)
- Come on, yuanuniverse. Sure enough, the heat won't pass for a while
- Research on personalized product search
- day39 原型链及页面烟花效果 2021.10.13
- Simple understanding of ThreadLocal
- 2022 open source software security status report: over 41% of enterprises do not have enough confidence in open source security
- Dongyuhui, New Oriental and Phoenix Satellite TV
- Practice and Thinking on the architecture of a set of 100000 TPS im integrated message system
猜你喜欢

If you want to change to software testing, how can you package your resume as a test engineer with 1 year of work experience

day36 js笔记 ECMA6语法 2021.10.09

The default point of this in JS and how to modify it to 2021.11.09

Multi dimensional monitoring: the data base of intelligent monitoring

js中this的默认指向及如何修改指向 2021.11.09

Is it feasible to be a programmer at the age of 26?

纯纯大怨种!那些年被劝退的考研专业

day32 js笔记 事件(上)2021.09.27

Swin, three degrees! Eth open source VRT: a transformer that refreshes multi domain indicators of video restoration
![[Beijing University of Aeronautics and Astronautics] information sharing for the first and second examinations of postgraduate entrance examination](/img/06/df5a64441814c9ecfa2f039318496e.jpg)
[Beijing University of Aeronautics and Astronautics] information sharing for the first and second examinations of postgraduate entrance examination
随机推荐
QML control type: tabbar
Prepare for Jin San Yin Si I. testers without experience in automated testing projects should look at it quickly
Day29 JS notes 2021.09.23
What is DAPP system development and analytical understanding
Day39 prototype chain and page Fireworks Effect 2021.10.13
Using MySQL database in the express framework of node
Many benefits of SEO optimization are directly related to traffic
Daily practice of C language - day 3: calculate the number of occurrences of sub strings of strings
Deployment and optimization of vsftpd service
【北京航空航天大学】考研初试复试资料分享
Prefix and (one dimension)
day29 js笔记 2021.09.23
Day31 JS notes DOM 2021.09.26
Setinterval, setTimeout and requestanimationframe
MapReduce项目案例1
MySQL cannot query the maximum value using the max function
【sciter】: sciter-fs模块扫描文件API的使用及其注意细节
On the output representation of bidirectional LSTM in pytoch
面试步骤的面试技巧
Day36 JS notes ecma6 syntax 2021.10.09