转自https://android.googlesource.com/platform/system/tools/aidl/+/brillo-m10-dev/docs/aidl-cpp.md。

Background

“aidl” refers to several related but distinct concepts:

  • the AIDL interface definition language
  • .aidl files (which contain AIDL)
  • the aidl generator which transforms AIDL into client/server IPC interfaces

The aidl generator is a command line tool that generates client and server stubs for Binder interfaces from a specification in a file with the .aidl extension. For Java interfaces, the executable is called aidl while for C++ the binary is called aidl-cpp. In this document, we’ll use AIDL to describe the language of .aidl files and aidl generator to refer to the code generation tool that takes an .aidl file, parses the AIDL, and outputs code.

Previously, the aidl generator only generated Java interface/stub/proxy objects. C++ Binder interfaces were handcrafted with various degrees of compatibility with the Java equivalents. The Brillo project added support for generating C++ with the aidl generator. This generated C++ is cross-language compatible (e.g. Java clients are tested to interoperate with native services).

Overview

This document describes how C++ generation works with attention to:

  • build interface
  • cross-language type mapping
  • implementing a generated interface
  • C++ parcelables
  • cross-language error reporting
  • cross-language null reference handling
  • cross-language integer constants

Detailed Design

Build Interface

Write AIDL in .aidl files and add them to LOCAL_SRC_FILES in your Android.mk. If your build target is a binary (e.g. you include $(BUILD_SHARED_LIBRARY)), then the generated code will be C++, not Java.

AIDL definitions should be hosted from the same repository as the implementation. Any system that needs the definition will also need the implementation (for both parcelables and interface). If there are multiple implementations (i.e. one in Java and one in C++), keep the definition with the native implementation. Android now has systems that run the native components of the system without the Java.
If you use an import statement in your AIDL, even from the same package, you need to add a path to LOCAL_AIDL_INCLUDES. This path should be relative to the root of the Android tree. For instance, a file IFoo.aidl defining com.example.IFoo might sit in a folder hierarchy something/something-else/com/example/IFoo.aidl. Then we would write:

  1. LOCAL_AIDL_INCLUDES := something/something-else

Generated C++ ends up in nested namespaces corresponding to the interface’s package. The generated header also corresponds to the interface package. So com.example.IFoo becomes ::com::example::IFoo in header “com/example/IFoo.h”.
Similar to how Java works, the suffix of the path to a .aidl file must match the package. So if IFoo.aidl declares itself to be in package com.example, the folder structure (as given to LOCAL_SRC_FILES
) must look like: some/prefix/com/example/IFoo.aidl
.
To generate code from .aidl files from another build target (e.g. another binary or java), just add a relative path to the .aidl files to LOCAL_SRC_FILES. Remember that importing AIDL works the same, even for code in other directory hierarchies: add the include root path relative to the checkout root to LOCAL_AIDL_INCLUDES.

Type Mapping

The following table summarizes the equivalent C++ types for common Java types and whether those types may be used as in/out/inout parameters in AIDL interfaces.

Java Type C++ Type inout Notes
boolean bool in "These 8 types are all considered primitives.
byte int8_t in  
char char16_t in  
int int32_t in  
long int64_t in  
float float in  
double double in  
String String16 in Supports null references.
android.os.Parcelable android::Parcelable inout  
T extends IBinder sp in  
Arrays (T[]) vector inout May contain only primitives, Strings and parcelables.
List vector inout  
PersistableBundle PersistableBundle inout binder/PersistableBundle.h
List vector<sp> inout  
FileDescriptor ScopedFd inout nativehelper/ScopedFd.h

Note that java.util.Map and java.utils.List are not good candidates for cross language communication because they may contain arbitrary types on the Java side. For instance, Map is cast to Map<String,Object> and then the object values dynamically inspected and serialized as type/value pairs. Support exists for sending arbitrary Java serializables, Android Bundles, etc.

Implementing a generated interface

Given an interface declaration like:

  1. package foo;
  2. import bar.IAnotherInterface;
  3. interface IFoo {
  4. IAnotherInterface DoSomething(int count, out List<String> output);
  5. }

aidl-cpp will generate a C++ interface:

  1. namespace foo {
  2. // Some headers have been omitted for clarity.
  3. #include <android/String16.h>
  4. #include <cstdint>
  5. #include <vector>
  6. #include <bar/IAnotherInterface.h>
  7. // Some class members have been omitted for clarity.
  8. class IFoo : public android::IInterface {
  9. public:
  10. virtual android::binder::Status DoSomething(
  11. int32_t count,
  12. std::vector<android::String16>* output,
  13. android::sp<bar::IAnotherInterface>* returned_value) = 0;
  14. };

Note that aidl-cpp
will import headers for types used in the interface. For imported types (e.g. parcelables and interfaces), it will import a header corresponding to the package/class name of the import. For instance, import bar.IAnotherInterface
causes aidl-cpp to generate #include <bar/IAnotherInterface.h>
.
When writing a service that implements this interface, write:

  1. #include "foo/BnFoo.h"
  2. namespace unrelated_namespace {
  3. class MyFoo : public foo::BnFoo {
  4. public:
  5. android::binder::Status DoSomething(
  6. int32_t count,
  7. std::vector<android::String16>* output,
  8. android::sp<bar::IAnotherInterface>* returned_value) override {
  9. for (int32_t i = 0; i < count; ++i) {
  10. output->push_back(String16("..."));
  11. }
  12. *returned_value = new InstanceOfAnotherInterface;
  13. return Status::ok();
  14. }
  15. }; // class MyFoo
  16. } // namespace unrelated_namespace

Note that the output values, output and returned_value are passed by pointer, and that this pointer is always valid.

C++ Parcelables

In Java, a parcelable should extend android.os.Parcelable and provide a static final CREATOR field that acts as a factory for new instances/arrays of instances of the parcelable. In addition, in order to be used as an out parameter, a parcelable class must define a readFromParcel method.
In C++, parcelables must implement android::Parcelable from binder/Parcelable.h in libbinder. Parcelables must define a constructor that takes no arguments. In order to be used in arrays, a parcelable must implement a copy or move constructor (called implicitly in vector).
The C++ generator needs to know what header defines the C++ parcelable. It learns this from the cpp_header
directive shown below. The generator takes this string and uses it as the literal include statement in generated code. The idea here is that you generate your code once, link it into a library along with parcelable implementations, and export appropriate header paths. This header include must make sense in the context of the Android.mk that compiles this generated code.
// ExampleParcelable.aidlpackage com.example.android;// Native types must be aliased at their declaration in the appropriate .aidl// file. This allows multiple interfaces to use a parcelable and its C++// equivalent without duplicating the mapping between the C++ and Java types.// Generator will assume bar/foo.h declares class// com::example::android::ExampleParcelableparcelable ExampleParcelable cpp_header "bar/foo.h";

Null Reference Handling

The aidl generator for both C++ and Java languages has been expanded to understand nullable annotations.
Given an interface definition like:

  1. interface IExample {
  2. void ReadStrings(String neverNull, in @nullable String maybeNull);
  3. };

the generated C++ header code looks like:

  1. class IExample {
  2. android::binder::Status ReadStrings(
  3. const android::String16& in_neverNull,
  4. const std::unique_ptr<android::String16>& in_maybeNull);
  5. };

Note that by default, the generated C++ passes a const reference to the value of a parameter and rejects null references with a NullPointerException sent back the caller. Parameters marked with @nullable are passed by pointer, allowing native services to explicitly control whether they allow method overloading via null parameters. Java stubs and proxies currently do nothing with the @nullable annotation.
Consider an AIDL type in @nullable List<String> bar. This type indicates that the remote caller may pass in a list of strings, and that both the list and any string in the list may be null. This type will map to a C++ type unique_ptr<vector<unique_ptr<String16>>>* bar
. In this case:

  • bar is never null
  • *bar might be null
  • (*bar)->empty() could be true
  • (**bar)[0] could be null (and so on)

Exception Reporting

C++ methods generated by the aidl generator return android::binder::Status objects, rather than android::status_t. This Status object allows generated C++ code to send and receive exceptions (an exception type and a String16 error message) since we do not use real exceptions in C++. More background on Status objects can be found here.

For legacy support and migration ease, the Status object includes a mechanism to report a android::status_t. However, that return code is interpreted by a different code path and does not include a helpful String message.

For situations where your native service needs to throw an error code specific to the service, use Status::fromServiceSpecificError(). This kind of exception comes with a helpful message and an integer error code. Make your error codes consistent across services by using interface constants (see below).

Integer Constants

AIDL has been enhanced to support defining integer constants as part of an interface:

  1. interface IMyInterface {
  2. const int CONST_A = 1;
  3. const int CONST_B = 2;
  4. const int CONST_C = 3;
  5. ...
  6. }

These map to appropriate 32 bit integer class constants in Java and C++ (e.g. IMyInterface.CONST_A
and IMyInterface::CONST_A
respectively).

C++ 下面的AIDL的更多相关文章

  1. eclipse 下面的folder,source folder,package的区别与作用

    首先明确一点,folder,source folder,package都是文件夹,既然是文件夹,那么任何的文件都可以往这三种文件夹下面的放.1.他们的区别folder就是普通的文件夹,它和我们wind ...

  2. 根据div 标签 查看数组@class=modulwrap 下面的/table/tbody/tr/td

    <div class="modulwrap"> <div class="request_title"> <span class=& ...

  3. jz2440: linux/arch/arm/下面的plat-和mach-

    jz2440: linux/arch/arm/下面的plat和mach plat-s3c24xxmach-s3c2440mach-s3c2410 ====================== 1. 三 ...

  4. syslog之三:建立Windows下面的syslog日志服务器

    目录: <syslog之一:Linux syslog日志系统详解> <syslog之二:syslog协议及rsyslog服务全解析> <syslog之三:建立Window ...

  5. webkit下面的CSS设置滚动条

    webkit下面的CSS设置滚动条 1.主要有下面7个属性: ::-webkit-scrollbar 滚动条整体部分,可以设置宽度啥的 ::-webkit-scrollbar-button 滚动条两端 ...

  6. Lazarus下面的javascript绑定另外一个版本bug修正

    Lazarus下面的javascript绑定另外一个版本bug修正 从svn 检出的代码有几个问题 1.fpcjs.pas 单元开始有 {$IFDEF FPC} {$MODE delphi} {$EN ...

  7. 给虚拟机下面的ubuntu系统增加硬盘存储空间

    给虚拟机下面的ubuntu系统增加硬盘存储空间   由于ubuntu系统是安装在vsphere上面的,所以可能会和vmware上面的有一点区别,打开exsi系统的配置页面,如下图所示. 选择添加存储器 ...

  8. Java:concurrent包下面的Map接口框架图(ConcurrentMap接口、ConcurrentHashMap实现类)

    Java集合大致可分为Set.List和Map三种体系,其中Set代表无序.不可重复的集合:List代表有序.重复的集合:而Map则代表具有映射关系的集合.Java 5之后,增加了Queue体系集合, ...

  9. Java:concurrent包下面的Collection接口框架图( CopyOnWriteArraySet, CopyOnWriteArrayList,ConcurrentLinkedQueue,BlockingQueue)

    Java集合大致可分为Set.List和Map三种体系,其中Set代表无序.不可重复的集合:List代表有序.重复的集合:而Map则代表具有映射关系的集合.Java 5之后,增加了Queue体系集合, ...

随机推荐

  1. Day 2: ASP.NET and python trying

    ASP.NET and Python/Javascript Many jQuery plugins that are designed and shared for free on the inter ...

  2. Python学习笔记第二十七周(Bootstrap)

    目录: 全局样式 一.栅格系统 二.表单 三.按钮  四.导航 五.按钮组 六.面板 七.表格 八.分页 九.排版 十.图片 十一.辅助类 十二.响应式工具 组件 内容: 前言: 首先通过https: ...

  3. 如何理解Minkowski不等式

    [转载请注明出处]http://www.cnblogs.com/mashiqi 2017/02/16 Minkowski不等式: 设$f$是$\mathbb{R}^n \times \mathbb{R ...

  4. Windows CMD 支持ls命令

    /********************************************************************** * Windows CMD 支持ls命令 * 说明: * ...

  5. restframework细节学习

    一.后端发送列表.字典 1. 发送字典出现safe error,需要如下处理 def books(request): ll=[{},{}] # return HttpResponse(json.dum ...

  6. [ Codeforces Round #549 (Div. 2)][D. The Beatles][exgcd]

    https://codeforces.com/contest/1143/problem/D D. The Beatles time limit per test 1 second memory lim ...

  7. CIFAR-10数据集读取

    参考:https://jingyan.baidu.com/article/656db9183296c7e381249cf4.html 1.使用读取方式pickle def unpickle(file) ...

  8. [转] Linux运维常见故障排查和处理的技巧汇总

    作为linux运维,多多少少会碰见这样那样的问题或故障,从中总结经验,查找问题,汇总并分析故障的原因,这是一个Linux运维工程师良好的习惯.每一次技术的突破,都经历着苦闷,伴随着快乐,可我们还是执着 ...

  9. LG1912 [NOI2009]诗人小G

    题意 题目描述 小G是一个出色的诗人,经常作诗自娱自乐.但是,他一直被一件事情所困扰,那就是诗的排版问题. 一首诗包含了若干个句子,对于一些连续的短句,可以将它们用空格隔开并放在一行中,注意一行中可以 ...

  10. 生产redis client 链接报:ERR max number of clients reached 含义: 达到最大客户端数错误

    1.通过netstat 命令查看TCP又11822个连接  (netstat命令是一个监控TCP/IP网络的非常有用的工具) 2.默认redis最大的连接数10000 ,但是此时无法连接redis客户 ...