Moosphan / Android-Daily-Interview

:pushpin:每工作日更新一道 Android 面试题,小聚成河,大聚成江,共勉之~

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

2019-09-06:什么是JNI?具体说说如何实现Java与C++的互调?

Moosphan opened this issue · comments

PS:可通过代码示例来说明Java与C++的调用过程。

我是来看答案的。

The Java Native Interface (JNI) is a standard to integrate in a portable way C++ and Java code. It works in both directions: you can call a C++ library from Java or you can call Java components from C++. In this tutorial, I'll explain the second approach.
How does this work?

  • We first have to find the right class with FindClass(), which acts as a class loader. It will search for an appropriate .class file in the list of directories that was provided at JVM initialization. If the Java class is included in a package, you shall provide its full name.

  • The class is then passed to GetStaticMethod(), which shall find the right method in the class. The last parameter of this function is the most difficult one: the method signature. In case of any mismatch here, the method won't be found. "()" means a function with no parameter and "V" that the return type is void.

  • A static method is independent of any object. So we can then call the method with CallStaticVoidMethod().

1: java 调用 c++ 方法, 通过 java类定义 native 方法, 使用javah 生成.h 头文件,定义cpp文件实现该方法, java 层就可以直接调用该方法了。
2: c++ 调用java 方法,分静态方法和非静态方法.
静态方法调用
JniHelper::callStaticStringMethod(classPath, "getAppName");
非静态方法调用
JniMethodInfo->CallVoidMethod(jobj,info.methodID,forceLogin);

  • 在Java类中声明native方法
  • 使用javac命令将Java类生成class文件
  • 使用javah文件生成头文件
  • 编写cpp文件实现jni方法
  • 生成so库
    到此为止,java就可以通过调用native方法调用c++函数了,对于在c++中调用java方法,
  • 通过完整类名获取jclass
  • 根据方法签名和名称获取构造方法id
  • 创建对象(如果要调用的是静态方法则不需要创建对象)
  • 获取对象某方法id
  • 通过JNIEnv根据返回值类型、是否是静态方法调用对应函数即可