Overview

JNI (Java Native Interface) is the mechanism that enables Java code to call native functions, and native code to call Java functions.

  • Native code calls into Java using apis from <jni.h>, which basically mirror Java's reflection APIs.
  • Java code calls native functions by declaring body-less functions with the native keyword, and then calling them as normal Java functions.

jni_generator generates boiler-plate code with the goal of making our code:

  1. easier to write, and
  2. typesafe.

jni_generator uses regular expressions to parse .Java files, so don't do anything too fancy. E.g.:

  • Classes must be either explicitly imported, or are assumed to be in the same package. To use java.lang classes, add an explicit import.
  • Inner classes need to be referenced through the outer class. E.g.: void call(Outer.Inner inner)

The presense of any JNI within a class will result in ProGuard obfuscation for the class to be disabled.

Exposing Native Methods

Without Crazy Linker:

  • Java->Native calls are exported from the shared library and lazily resolved by the runtime (via dlsym()).

With Crazy Linker:

  • Java->Native calls are explicitly registered with JNI on the native side. Explicit registration is necessary because crazy linker provides its own dlsym(), but JNI is hardcoded to use the system's dlsym().

    • The logic to explicitly register stubs is generated by jni_registration_generator.py.

      • This script finds all native methods by scanning all source .java files of an APK. Inefficient, but very convenient.
    • Since dlsym() is not used in this case, we use a linker script to avoid the cost of exporting symbols from the shared library (refer to //build/config/android:hide_all_but_jni_onload).
  • jni_registration_generator.py exposes two registrations methods:
    • RegisterNonMainDexNatives - Registers native functions needed by multiple process types (e.g. Rendereres, GPU process).
    • RegisterMainDexNatives - Registers native functions needed only by the browser process.

Exposing Java Methods

Java methods just need to be annotated with @CalledByNative. The generated functions can be put into a namespace using @JNINamespace("your_namespace").

Usage

Because the generator does not generate any source files, generated headers must not be #included by multiple sources. If there are Java functions that need to be called by multiple sources, one source should be chosen to expose the functions to the others via additional wrapper functions.

Calling Java -> Native

  • Methods marked as native will have stubs generated for them that forward calls to C++ function (that you must write).
  • If the first parameter is a C++ object (e.g. long mNativePointer), then the bindings will automatically generate the appropriate cast and call into C++ code (JNI itself is only C).

Calling Native -> Java

  • Methods annotated with @CalledByNative will have stubs generated for them.
  • Just call the generated stubs defined in generated .h files.

Java Objects and Garbage Collection

All pointers to Java objects must be registered with JNI in order to prevent garbage collection from invalidating them.

For Strings & Arrays - it's common practice to use the //base/android/jni_* helpers to convert them to std::vectors and std::strings as soon as possible.

For other objects - use smart pointers to store them:

  • ScopedJavaLocalRef<> - When lifetime is the current function's scope.
  • ScopedJavaGlobalRef<> - When lifetime is longer than the current function's scope.
  • JavaObjectWeakGlobalRef<> - Weak reference (do not prevent garbage collection).
  • JavaParamRef<> - Use to accept any of the above as a parameter to a function without creating a redundant registration.

Additional Guidelines / Advice

Minimize the surface API between the two sides. Rather than calling multiple functions across boundaries, call only one (and then on the other side, call as many little functions as required).

If a Java object “owns” a native one, store the pointer via "long mNativeClassName". Ensure to eventually call a native method to delete the object. For example, have a close() that deletes the native object.

The best way to pass “compound” types across in either direction is to create an inner class with PODs and a factory function. If possible, make mark all the fields as “final”.

Build Rules

  • generate_jni - Generates a header file with stubs for given .java files
  • generate_jar_jni - Generates a header file with stubs for a given .jar file
  • generate_jni_registration - Generates a header file with functions to register native-side JNI methods (required only when using crazy linker).

Refer to //build/config/android/rules.gni for more about the GN templates.

Changing jni_generator

  • Python unit tests live in jni_generator_tests.py
  • A working demo app exists as //base/android/jni_generator:sample_jni_apk

[Chromium文档转载,第007章]JNI on Chromium for Android的更多相关文章

  1. [Chromium文档转载,第003章]Proposal: Mojo Synchronous Methods

    Proposal: Mojo Synchronous Methods yzshen@chromium.org 02/02/2016 Overview Currently there are quite ...

  2. [Chromium文档转载,第002章]Mojo C++ Bindings API

    Mojo C++ Bindings API This document is a subset of the Mojo documentation. Contents Overview Getting ...

  3. [Chromium文档转载,第001章] Mojo Migration Guide

        For Developers‎ > ‎Design Documents‎ > ‎Mojo‎ > ‎ Mojo Migration Guide 目录 1 Summary 2 H ...

  4. [Chromium文档转载,第006章]Chrome IPC To Mojo IPC Cheat Sheet

    For Developers‎ > ‎Design Documents‎ > ‎Mojo‎ > ‎ Chrome IPC To Mojo IPC Cheat Sheet 目录 1 O ...

  5. [Chromium文档转载,第005章]Calling Mojo from Blink

    For Developers‎ > ‎Design Documents‎ > ‎Mojo‎ > ‎ Calling Mojo from Blink Variants Let's as ...

  6. [Chromium文档转载,第004章]Mojo Synchronous Calls

    For Developers‎ > ‎Design Documents‎ > ‎Mojo‎ > ‎ Synchronous Calls Think carefully before ...

  7. 用R创建Word和PowerPoint文档--转载

    https://www.jianshu.com/p/7df62865c3ed Rapp --简书 Microsoft的Office软件在办公软件领域占有绝对的主导地位,几乎每个职场人士都必须掌握Wor ...

  8. java实现支付宝接口--文档..转载

    //实现java支付宝很简单,只要从支付宝官方下载   http://help.alipay.com/support/index_sh.htm下载程序,配置一下参数就OK了:   1.先到http:/ ...

  9. iOS开发主要参考文档(转载)

    Objective-C,语言的系统详细资料.这是做iOS开发的前题与基础.https://developer.apple.com/library/ios/#documentation/Cocoa/Co ...

随机推荐

  1. [terry笔记]redhat5.5_11gR2_RAC_安装

    redhat5.5_11gR2_RAC_安装,这篇主要记录RAC安装的执行步骤,最烦琐的就是前期配置,到后面图形界面runInstaller,asmca,dbca就很容易了. --hostname检查 ...

  2. android-async-http二次封装和调用

    Android  android-async-http二次封装和调用 在开发过程中,网络请求这块的使我们常常遇到的一个问题,今天去github 站点上面学习android-async-http,认为还 ...

  3. Mock+Proxy在SDK项目的自己主动化測试实战

    项目背景 广告SDK项目是为应用程序APP开发者提供移动广告平台接入的API程序集合,其形态就是一个植入宿主APP的jar包.提供的功能主要有以下几点: - 为APP请求广告内容 - 用户行为打点 - ...

  4. powershell无法拖动文件到命令行

    PS C:\Program Files\PowerShell\6.0.0-beta.6> New-Service -Name LISA_43_Dev_Batch -DisplayName LIS ...

  5. How to: Create Custom Configuration Sections Using ConfigurationSection

    https://msdn.microsoft.com/en-us/library/2tw134k3.aspx You can extend ASP.NET configuration settings ...

  6. Dictionaries and lists

    Lists can appear as values in a dictionary. For example, if you were given a dictionary that maps fr ...

  7. Lists are mutable

    The syntax for accessing the elements of a list is the same as for accessing the characters of a str ...

  8. [转]60fps on the mobile web

    Flipboard launched during the dawn of the smartphone and tablet as a mobile-first experience, allowi ...

  9. Andoid 更好的Android多线程下载框架

    概述 为什么是更好的Android多线程下载框架呢,原因你懂的,广告法嘛! 本篇我们我们就来聊聊多线程下载框架,先聊聊我们框架的特点: 多线程 多任务 断点续传 支持大文件 可以自定义下载数据库 高度 ...

  10. 深入理解 sudo 与 su 之间的区别

    深入理解 sudo 与 su 之间的区别 作者: Himanshu Arora 译者: LCTT zhb127 在早前的一篇文章中,我们深入讨论了 sudo 命令的相关内容.同时,在该文章的末尾有提到 ...