1# Cargo2gn工具操作指导 2## 概述 3 4rust三方库使用cargo编译,配置为Cargo.toml。集成到OpenHarmony上需要转换成BUILD.gn规则。为了满足这个需求,需要提供一个cargo2gn转换工具。当需要引入rust三方crate时使用cargo2gn转换工具来把三方库的Cargo.toml转换成BUILD.gn规则。cargo2gn可以单个库进行转换,也可以多个库进行批量转换。 5 6## 单个库转换操作步骤 71. 进入到需要转化的rust三方库的目录下,比如需要转化bindgen。 8 9 ``` 10 cd openharmony/third_party/rust/bindgen 11 ``` 12 132. 创建配置文件cargo2gn.json,可以参考如下配置。 14 15 ```json 16 { 17 "copy-out": true, 18 "run": true, 19 "add-workspace": true, 20 "cargo-bin": "/mnt/xxx/openharmony/prebuilts/rustc/linux-x86_64/current/bin" 21 } 22 ``` 23 243. 执行以下命令进行转换。 25 26 ``` 27 python3 /mnt/xxx/openharmony/build/scripts/cargo2gn.py --config cargo2gn.json 28 ``` 29 30 转换结果 31 32 ``` 33 import("//build/templates/rust/ohos_cargo_crate.gni") 34 35 ohos_cargo_crate("lib") { 36 crate_name = "bindgen" 37 crate_type = "rlib" 38 crate_root = "./lib.rs" 39 40 sources = ["./lib.rs"] 41 edition = "2018" 42 cargo_pkg_version = "0.64.0" 43 cargo_pkg_authors = "Jyun-Yan You <jyyou.tw@gmail.com>, Emilio Cobos Álvarez <emilio@crisal.io>, Nick Fitzgerald <fitzgen@gmail.com>, The Servo project developers" 44 cargo_pkg_name = "bindgen" 45 cargo_pkg_description = "Automatically generates Rust FFI bindings to C and C++ libraries." 46 deps = [ 47 "//third_party/rust/bitflags:lib", 48 "//third_party/rust/cexpr:lib", 49 "//third_party/rust/clang-sys:lib", 50 "//third_party/rust/lazy_static:lib", 51 "//third_party/rust/lazycell:lib", 52 "//third_party/rust/log:lib", 53 "//third_party/rust/peeking_take_while:lib", 54 "//third_party/rust/proc-macro2:lib", 55 "//third_party/rust/quote:lib", 56 "//third_party/rust/regex:lib", 57 "//third_party/rust/rustc-hash:lib", 58 "//third_party/rust/shlex:lib", 59 "//third_party/rust/syn:lib", 60 "//third_party/rust/which:lib", 61 ] 62 features = [ 63 "default", 64 "log", 65 "logging", 66 "static", 67 "which", 68 "which-rustfmt", 69 ] 70 build_root = "build.rs" 71 build_sources = ["build.rs"] 72 build_script_outputs = ["host-target.txt"] 73 } 74 ``` 75 76 77 78## 多个库批量转换操作步骤 791. 进入到rust目录下。 80 81 ``` 82 cd openharmony/third_party/rust 83 ``` 842. 把所有需要转换的rust三方库添加到rust目录下的Cargo.toml的[workspace]里,如下所示。 85 86 ```toml 87 [workspace] 88 members = [ 89 "aho-corasick", 90 "memchr", 91 ] 92 ``` 933. 执行单个库转换操作步骤的2和3。 94 95