【入门到实战】OpenHarmony南向开发:Rust编译构建指南-Cargo2gn工具操作

OpenHarmony4.0的Rust开发 Rust 是一门静态强类型语言,具有更安全的内存管理、更好的运行性能、原生支持多线程开发等优势。Rust 官方也使用 Cargo 工具来专门为 Rust 代码创建工程和构建编译。OpenHarmony 为了集成 C/C++ 代码和提升编译速度,使用了 GN + Ninja 的编译构建系统。GN 的构建语言简洁易读,Ninja 的汇编级编译规则直接高效。 阅读详情

往期鸿蒙5.0全套实战文章必看:(文中附带全栈鸿蒙5.0学习资料)


Cargo2gn工具操作

概述

rust三方库使用cargo编译,配置为Cargo.toml。集成到OpenHarmony上需要转换成BUILD.gn规则。为了满足这个需求,需要提供一个cargo2gn转换工具。当需要引入rust三方crate时使用cargo2gn转换工具来把三方库的Cargo.toml转换成BUILD.gn规则。cargo2gn可以单个库进行转换,也可以多个库进行批量转换。

单个库转换操作步骤

  1. 进入到需要转化的rust三方库的目录下,比如需要转化bindgen。

    cd openharmony/third_party/rust/bindgen
    
  2. 创建配置文件cargo2gn.json,可以参考如下配置。

    {
        "copy-out": true,
        "run": true,
        "add-workspace": true,
        "cargo-bin": "/mnt/xxx/openharmony/prebuilts/rustc/linux-x86_64/current/bin"
    }
    
  3. 执行以下命令进行转换。

    python3 /mnt/xxx/openharmony/build/scripts/cargo2gn.py --config cargo2gn.json
    

    转换结果

    import("//build/templates/rust/ohos_cargo_crate.gni")
    
    ohos_cargo_crate("lib") {
        crate_name = "bindgen"
        crate_type = "rlib"
        crate_root = "./lib.rs"
    
        sources = ["./lib.rs"]
        edition = "2018"
        cargo_pkg_version = "0.64.0"
        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"
        cargo_pkg_name = "bindgen"
        cargo_pkg_description = "Automatically generates Rust FFI bindings to C and C++ libraries."
        deps = [
            "//third_party/rust/bitflags:lib",
            "//third_party/rust/cexpr:lib",
            "//third_party/rust/clang-sys:lib",
            "//third_party/rust/lazy_static:lib",
            "//third_party/rust/lazycell:lib",
            "//third_party/rust/log:lib",
            "//third_party/rust/peeking_take_while:lib",
            "//third_party/rust/proc-macro2:lib",
            "//third_party/rust/quote:lib",
            "//third_party/rust/regex:lib",
            "//third_party/rust/rustc-hash:lib",
            "//third_party/rust/shlex:lib",
            "//third_party/rust/syn:lib",
            "//third_party/rust/which:lib",
        ]
        features = [
            "default",
            "log",
            "logging",
            "static",
            "which",
            "which-rustfmt",
        ]
        build_root = "build.rs"
        build_sources = ["build.rs"]
        build_script_outputs = ["host-target.txt"]
    }
    

多个库批量转换操作步骤

  1. 进入到rust目录下。

    cd openharmony/third_party/rust
    
  2. 把所有需要转换的rust三方库添加到rust目录下的Cargo.toml的[workspace]里,如下所示。

    [workspace]
    members = [
        "aho-corasick",
        "memchr",
    ]
    
  3. 执行单个库转换操作步骤的2和3。

OpenHarmony Rust模块配置指南:构建安全高效的鸿蒙原生应用 在嵌入式系统与物联网设备开发中,内存安全与系统稳定性是核心诉求。Rust语言通过其独特的所有权系统和编译时检查机制,从原理上杜绝了空指针解引用、数据竞争等常见内存错误,为构建高可靠性系统提供了底层保障。这一技术价值在要求长期稳定运行的工业控制、智能终端等场景中尤为突出。通过FFI(外部函数接口)技术,Rust模块能够与现有的C/C++生态安全交互,实现能力复用与性能互补。本文将聚焦于OpenHarmony操作系统这一具体应用场景,深入解析如何通过GN构建系统,将Rust代码以静态库或动态库的形式,高效集成到 阅读详情

相关推荐

OpenHarmony Rust模块配置实战:从FFI到系统集成的完整指南

在系统级软件开发中,内存安全和并发控制是保障软件可靠性的核心挑战。传统C/C++语言在编译时难以完全检测内存越界、数据竞争等隐患,这些隐患往往在运行时才暴露,对嵌入式、物联网等高可靠性场景构成风险。Rust语言通过所有权系统、借用检查器和零成本抽象等机制,在编译阶段即可消除大部分内存错误和并发问题,为系统软件提供了从根源上提升安全性的工程范式。其价值在需要长期稳定运行的智能终端、车载系统、工业控制等场景尤为突出。本文聚焦于Rust与OpenHarmony构建系统的集成,详细解析如何通过Gn脚本和Cargo.

weixin_33725126的博客 218

Rust交叉编译OpenHarmony应用动态库

rust 编译 openharmony 动态库

zrufo747的博客 1580

鸿蒙开发实战:【ylong_http】解析

ylong_http 构建了完整的 HTTP 能力,支持用户使用 HTTP 能力完成通信场景的需求。ylong_http 使用 Rust 编写,为 OpenHarmony 的 Rust 能力构筑提供支持。

m0_62167422的博客 1397

OpenHarmony4.1上初体验rust

ubuntu20.04搭建RUST开发环境并与C语言交互需要了解OopenHarmony,HDC,ninja编译体系构建。熟悉rust语言,rust编译。

qqq1112345的博客 1680

鸿蒙网络开发学习:【ylong_http】

ylong_http 构建了完整的 HTTP 能力,支持用户使用 HTTP 能力完成通信场景的需求。ylong_http 使用 Rust 编写,为 OpenHarmony 的 Rust 能力构筑提供支持。

m0_62167422的博客 1436

鸿蒙OpenHarmony【交互工具使用】子系统

Bindgen和CXX工具的主要功能是实现Rust和C/C++之间的交互。其中,Bindgen通过将C接口转换为Rust接口来实现Rust对C的调用,CXX可以通过建立C接口和Rust接口的映射关系来实现C++和Rust的相互调用。

zxc95279527q的博客 671

HarmonyOS RUST 应用开发指导

开发者在进行鸿蒙应用开发时,希望用 Rust 构建部分应用模块以获得应用在运行性能、安全等方面的提升,或者开发者希望将三方 Rust 模块进行鸿蒙化。虽然Rust主线版本已经支持 OpenHarmony,但当前Rust对于 OpenHarmony 为 tier3 支持,无法使用 rustup 下载到 OpenHarmony 对应的 std 标准库。所以推荐使用 rust nightly 版本实时构建std标准库,此方式会默认将 OpenHarmony 的 std 和 Rust 模块静态链接。

BelanLu的博客 4898

OpenHarmony南向设备开发:Rust远程调试

由于使用Rust语言开发OpenHarmony系统服务需要在远端(Linux端)进行..........

初一十五的博客 939

用Rust开发鸿蒙应用(ArkTS NAPI)

为ArkUI添加Rust支持

zrufo747的博客 5314

rust 交叉编译环境搭建

rust 交叉编译环境搭建

yeamon的博客 1600

《OpenHarmony4.1上初体验rust》 文章代码

rust在OH系统里的测试代码,包括helloworld,bindgen实现Rust调用C,C++和Rust互调。 参考文章:https://editor.youkuaiyun.com/md/?not_checkout=1&articleId=141155817 在build\rust\tests\BUILD.gn中添加 group("test_liusai") { deps = [ "test_liusai:test_bin_liusai", "test_liusai:test_liusai_cxx_exe", ] } 然后使用./build.sh --product-name ***--no-prebuilt-sdk --build-target rust_liusai命令编译后讲产物放到设备上运行金科。

OpenHarmony子系统开发 - Rust编译构建指导

本文用于指导 Rust 语言开发者编译构建 OpenHarmony OS Rust 应用程序。Rust 是一门静态强类型语言,具有更安全的内存管理、更好的运行性能、原生支持多线程开发等优势。本工具链基于开源 rust 与 llvm 增量开发,适配了 OpenHarmony OS target 二进制构建。可将 rust 源码编译成能在 OpenHarmony OS 设备上使用的目标二进制。rust三方库使用cargo编译,配置为Cargo.toml。

__Benco的博客 1420

基于FT2232集成USB直接实现XilinxJTAG和UART串口

使用“program_ftdi -write -ftdi FT2232H -serial 0ABC01 -vendor "my vendor co" -board "my board" -desc "my product desc"”命令进行数据烧写,该命令会将FT2232的通道A配置为JTAG,其余通道配置为UART,serial长度为6~12个字符(vivado扫描JTAG时显示的cable序列号,同一台PC能够同时连接多个不同序列号的cable仿真器)。图 2 program_ftdi的帮助信息。

luguodeyo的博客 1万+

鸿蒙OpenHarmony开发板解析:【Rust模块配置规则和指导】

鸿蒙是完全具备无与伦比的机遇和潜力的;预计到年底将有 5,000 款的应用完成原生鸿蒙开发,这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才。鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行!

m0_62167422的博客 1671

接入 deepseek 实现AI智能问诊

必须包含user角色,用于传递用户输入。system角色可选,用于设置对话背景。多轮对话需要将历史记录添加到messages中。

weixin_51326478的博客 6545

使用单片机和电流互感器对非正弦周期电流有效值测定

使用单片机和电流互感器,利用一种高速采样的方法来进行有效值测定

月光绿叶滴水音乐 3950

在OpenHarmony中使用 C/C++/Rust进行应用开发

本文档是一份由移远通信技术股份有限公司提供的技术指南,基于OpenHarmony 5.0.3版本,详细介绍了如何在OpenHarmony系统中开发C/C++/Rust编写的ELF可执行程序。文档主要面向嵌入式应用开发场景,不涉及用户界面显示,专注于底层功能模块的兼容性和性能优化

qq_39798759的博客 1265

评分卡建模学习(一)————数据预处理part.3

目录六、数据处理的思路及代码(一)对缺失值的处理:在我这个数据预处理的part.1板块(二)对异常值的处理:在我这个数据预处理的part.2板块(三)数据归一化、标准化:在我这个数据预处理的part.2板块(四)非结构化数据转变+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++———————————————————————————————————————————++++++++++++++++++++++++++

Morven_dai的博客 898

无需云服务的家庭相册:OpenHarmony 上的 Rust 实践

摘要: 本项目基于国产香橙派5硬件和OpenHarmony系统,采用Rust语言开发全栈私有化家庭相册系统。核心功能包括多设备照片上传、智能去重、时间轴展示,支持本地存储与自动备份。系统通过USB硬盘扩展存储,以SQLite管理数据,提供PWA网页端访问。方案实现完全国产化(RK3588S芯片+OpenHarmony+Rust),数据不出本地网络,待机功耗仅5W。未来可扩展AI能力与分布式同步,兼顾隐私安全与易用性。

软件行业技术文化交流。 1219

【AAAI 2025】轻量级特征增强新范式!FCM 模块助力小目标检测,即插即用提升模型泛化能力

本文介绍了AAAI 2025提出的轻量级特征增强新范式FCM模块,它通过显式分离并双向交互语义与空间特征,有效解决了小目标检测中特征信息失配的核心难题。该模块设计精巧,计算开销极低,能够即插即用式地嵌入YOLO等主流检测网络,显著提升模型对小目标的泛化检测能力,尤其适用于遥感、自动驾驶等对计算资源敏感的实际场景。

weixin_29056145的博客 291

用 Python 和 uiautomation 实现微信批量发送

思路是这样,将要发送的人员名单(包括称呼)以及发送内容都维护到Excel里,程序运行时读取Excel里内容,自动搜索人员姓名(微信昵称或备注名),填入要发送的内容,拼接上称呼(如果需要的话)自动点击发送,这样轮巡直至名单人员全部发送完成。、

jankingdom的专栏 1471

2022年,Rust将成为Linux 内核第二官方语言吗?

日前,Linux 内核和 Rust on Linux 的主要开发者 Miguel Ojeda 向 Linux Kernel 邮件列表提交了一个新补丁 (v2),进一步推进了 Rust for Linux 的工作进展。邮件内容指出,新的补丁将为 Linux 内核增加对 Rust 作为第二语言的支持,并且对 Rust 的整体支持进行了多项改进。具体来说,Rust 代码现在已经依赖于稳定的 Rust 编译器而不是之前的 beta 版本状态。

嵌入式Linux内核的博客 1796

ABAP_自定义屏幕07—下拉列表框

ABAP_自定义屏幕07—下拉列表框 完成以下:页面中有下拉列表框,下拉框value=系统表SCRR的值 1、实现方法A-常用 1.1 在主程序定义字段 TYPES:BEGIN OF type_carrid, carrid LIKE scarr-carrid,"航线代码 carrname LIKE scarr-carrname,"航向名称 END OF type_carrid. DATA g_it_carrid TYPE STANDARD TABLE OF type_carrid

f346348157的博客 3873

【社区投稿】Rust登陆华为鸿蒙操作系统之Native模块开发

Rust登陆【华为鸿蒙】操作系统之Native模块开发名词解释【鸿蒙操作系统】的英文全名是Open Harmony Operation System。正文将以其首字母缩写词ohos引用该词条。【鸿蒙软件开发工具包】的英文全名是Open Harmony Software Development Kit。正文也将以它的首字母缩写词ohsdk引用该词条。DevEco Studio IDE是【华为】为鸿蒙...

Rust语言学习交流 3774

计算机视觉教程1-1:透视空间与透视变换

在生活中,透视现象很常见,其物理本质是光的直线传播。由于人眼与相机在捕获图像时均存在透视现象,因此计算机几何基于透视空间进行研究。本节介绍透视变换原理

FRIGIDWINTER的博客 3094

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

OpenHarmony实战开发-FaultLoggerd组件。

Faultloggerd部件是OpenHarmony中C/C++运行时崩溃临时日志的生成及管理模块。面向基于 Rust 开发的部件,Faultloggerd 提供了Rust Panic故障日志生成能力。系统开发者可以在预设的路径下找到故障日志,定位相关问题。

m0_70749039的博客 1137

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 【入门到实战】OpenHarmony南向开发:Rust编译构建指南-交互工具使用
下一篇: 【入门到实战】OpenHarmony南向子系统开发:窗口标题栏定制开发指导(ArkTS)
懂你的大海
博客等级 码龄6年 9049粉丝 1381原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值