Flutter Rust Bridge 中 Rust 调用 Dart 回调的实现与线程安全
在 Flutter Rust Bridge 项目中,开发者经常需要实现 Rust 与 Dart 之间的双向通信。本文将深入探讨如何在 Rust 中存储和调用 Dart 回调函数,并解决相关的线程安全问题。
问题背景
在跨语言交互中,Rust 调用 Dart 回调是一种常见需求。开发者希望将 Dart 回调函数存储在 Rust 结构中,以便后续调用。这种模式在事件处理等场景中尤为有用。
基础实现
最简单的实现方式是直接定义一个接受 Dart 回调的 Rust 异步函数:
pub async fn rust_function(dart_callback: impl Fn(String) -> DartFnFuture<String>) {
dart_callback("Tom".to_owned()).await;
}
然而,当我们需要将回调存储在结构体中时,情况会变得复杂。
结构体存储回调的实现
为了将回调存储在结构体中,我们需要使用 Arc 和 Mutex 来确保线程安全:
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use flutter_rust_bridge::DartFnFuture;
pub struct FfiEvent {
msg_cb: Arc<Mutex<Box<dyn Fn(Vec<u8>, String, String) -> DartFnFuture<bool> + Send + 'static>>>,
}
impl FfiEvent {
pub fn new(
msg_cb: impl Fn(Vec<u8>, String, String) -> DartFnFuture<bool> + 'static + Send,
) -> Self {
Self {
msg_cb: Arc::new(Mutex::new(Box::new(msg_cb))),
}
}
}
线程安全问题
上述实现会遇到编译错误,提示 future cannot be sent between threads safely。这是因为标准库的 MutexGuard 在跨 await 点时无法保证 Send 特性。
解决方案:使用 Tokio 的 Mutex
解决方法是使用 Tokio 提供的异步 Mutex,它专为异步上下文设计:
use tokio::sync::Mutex; // 替换标准库的 Mutex
pub struct FfiEvent {
msg_cb: Arc<Mutex<Box<dyn Fn(Vec<u8>, String, String) -> DartFnFuture<bool> + Send + 'static>>>,
}
#[async_trait]
impl Event for FfiEvent {
async fn message_event(&self, from: String, message: Vec<u8>, message_id: String) -> bool {
let cb = self.msg_cb.lock().await; // 注意这里使用 .await 而不是 .unwrap()
cb(message, from, message_id).await
}
}
实现 Event 特质
完整的实现还需要定义一个异步特质 (trait):
#[async_trait]
pub trait Event: Send {
async fn message_event(&self, from: String, message: Vec<u8>, message_id: String) -> bool;
// 其他方法...
}
关键点总结
-
线程安全:在异步环境中,标准库的同步原语可能导致问题,应使用异步友好的替代品。
-
生命周期管理:回调需要明确的
'static生命周期标记,确保它们比持有它们的结构体存活更久。 -
Send 特性:所有跨线程使用的类型都必须实现
Send特性。 -
错误处理:异步锁使用
await而不是unwrap(),因为锁可能被异步地持有。
最佳实践建议
-
对于复杂的回调场景,考虑使用消息通道 (channel) 替代直接回调。
-
在性能敏感的场景,评估锁的开销,可能需要无锁数据结构。
-
为回调添加日志记录,便于调试跨语言调用问题。
-
考虑使用类型别名简化复杂的回调类型签名。
通过以上方法,开发者可以在 Flutter Rust Bridge 项目中安全高效地实现 Rust 调用 Dart 回调的功能,构建强大的跨语言交互系统。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0218
cann-learning-hubCANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。Jupyter Notebook0139
uni-appA cross-platform framework using Vue.jsJavaScript09
GLM-5.2智谱开源 GLM-5.2,这是针对长文本任务的最新旗舰模型。相较于前代产品 GLM-5.1,它在长文本任务处理能力上实现了显著飞跃,并且首次在稳定的 100 万 token 上下文中提供这一能力。Jinja00
SwanLab⚡️SwanLab - an open-source, modern-design AI training tracking and visualization tool. Supports Cloud / Self-hosted use. Integrated with PyTorch / Transformers / LLaMA Factory / veRL/ Swift / Ultralytics / MMEngine / Keras etc.Python00
tiny-universe《大模型白盒子构建指南》:一个全手搓的Tiny-UniverseJupyter Notebook03