首页
/ Flutter Rust Bridge 中 Rust 调用 Dart 回调的实现与线程安全

Flutter Rust Bridge 中 Rust 调用 Dart 回调的实现与线程安全

2025-06-13 00:31:58作者:董斯意

在 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;
}

然而,当我们需要将回调存储在结构体中时,情况会变得复杂。

结构体存储回调的实现

为了将回调存储在结构体中,我们需要使用 ArcMutex 来确保线程安全:

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;
    // 其他方法...
}

关键点总结

  1. 线程安全:在异步环境中,标准库的同步原语可能导致问题,应使用异步友好的替代品。

  2. 生命周期管理:回调需要明确的 'static 生命周期标记,确保它们比持有它们的结构体存活更久。

  3. Send 特性:所有跨线程使用的类型都必须实现 Send 特性。

  4. 错误处理:异步锁使用 await 而不是 unwrap(),因为锁可能被异步地持有。

最佳实践建议

  1. 对于复杂的回调场景,考虑使用消息通道 (channel) 替代直接回调。

  2. 在性能敏感的场景,评估锁的开销,可能需要无锁数据结构。

  3. 为回调添加日志记录,便于调试跨语言调用问题。

  4. 考虑使用类型别名简化复杂的回调类型签名。

通过以上方法,开发者可以在 Flutter Rust Bridge 项目中安全高效地实现 Rust 调用 Dart 回调的功能,构建强大的跨语言交互系统。

登录后查看全文
热门项目推荐