HLCPP 对象美观打印

前提条件

本教程以编译 FIDL 教程为基础。如需查看完整的 FIDL 教程,请参阅概览

概览

本教程介绍了如何使用 fostr 工具将调试打印功能添加到 HLCPP 类型中。

如果您要自行编写代码,请删除以下目录:

rm -r examples/fidl/hlcpp/fostr farnet/public/lib/fostr/fidl

本教程包含以下步骤:

  • 为 FIDL 库定义 fostr_fidl 目标。这样,您就可以为每种类型定义一个 operator<<,从而针对库中的类型进行调试输出。
  • 使用 fostr_fidl 目标。
  • 使用格式化程序代码编写示例。

定义 fostr_fidl 目标

  1. //src/lib/fostr/fidl 内为 BUILD 文件创建一个目录:

    mkdir -p src/lib/fostr/fidl/fuchsia.examples
    
  2. 创建 BUILD 文件:

    touch src/lib/fostr/fidl/fuchsia.examples/BUILD.gn
    
  3. 将以下定义添加到 build 文件中:

    # Copyright 2020 The Fuchsia Authors. All rights reserved.
    # Use of this source code is governed by a BSD-style license that can be
    # found in the LICENSE file.
    
    import("//src/lib/fostr/build/fostr_fidl.gni")
    fostr_fidl("fuchsia.examples") {
      fidl_target = "//examples/fidl/fuchsia.examples"
    }
    
    

这为 fuchsia.examples 库定义了 fostr 目标。该库的任何依赖项也需要在 build 文件中指定,这不适用于本教程,因为它没有依赖项。如需查看更复杂的示例,请参阅 fostr fidl 目录中的现有定义。

添加对 fostr_fidl 目标的依赖项

本教程使用的目标库是一个简单的主机测试,位于 examples/fidl/hlcpp/fostr 中。请注意,测试的 BUILD 文件将 fostr_fidl 目标添加为依赖项:

executable("bin") {
  testonly = true
  output_name = "fostr_example_test"
  sources = [ "main.cc" ]
  deps = [
    "//examples/fidl/fuchsia.examples:fuchsia.examples_hlcpp",
    "//src/lib/fostr/fidl/fuchsia.examples",
    "//src/lib/fxl/test:gtest_main",
  ]
}

所包含的库会自动使 << 运算符重载。路径取决于为其生成的 FIDL 库的名称:

#include <src/lib/fostr/fidl/fuchsia/examples/formatting.h>

使用格式化程序代码编写示例

编写一些占位符测试来展示输出:

TEST(FidlExamples, Bits) {
  auto flags = fuchsia::examples::FileMode::READ | fuchsia::examples::FileMode::WRITE;
  std::cout << flags << std::endl;
}

TEST(FidlExamples, Enums) {
  auto enum_val = fuchsia::examples::LocationType::MUSEUM;
  std::cout << enum_val << std::endl;
}

TEST(FidlExamples, Structs) {
  fuchsia::examples::Color default_color;
  std::cout << default_color << std::endl;
}

TEST(FidlExamples, Unions) {
  auto int_val = fuchsia::examples::JsonValue::WithIntValue(1);
  std::cout << int_val << std::endl;
}

运行示例

如需运行此示例,请执行以下操作:

  1. 配置 GN build 以包含示例:

    fx set core.x64  --with //examples/fidl/hlcpp/fostr
    
  2. 运行测试:

    fx test -vo fostr-example-test