Guide · 03 Typed RPC
强类型服务桥接 (ServiceRegistry & Bindings)
无需过程宏污染与权限配置文件,直接注册并调用强类型 Rust 函数。
告别繁琐的 IPC 宏与权限碎片
在传统框架中,暴露一个后端函数往往需要添加属性宏、在入口数组中重复注册,还要在能力 JSON 文件中手动声明权限。GPUX 提供极简的 ServiceRegistry 与 App::bind。
注册与调用强类型服务
rust
use gpux::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct CreateNoteReq {
pub title: String,
pub tags: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NoteCreatedRes {
pub id: u64,
pub summary: String,
}
fn main() -> anyhow::Result<()> {
let mut services = ServiceRegistry::new();
// 1. 直接绑定任意满足 Serialize / DeserializeOwned 的闭包或函数
services.register("notes.create", |req: CreateNoteReq| {
Ok(NoteCreatedRes {
id: 1024,
summary: format!("Created '{}' with {} tags", req.title, req.tags.len()),
})
});
// 2. 在 GPUI 视图或插件中以编译期强类型直接调用(进程内 ~1.2µs 延迟)
let res: NoteCreatedRes = services.call(
"notes.create",
CreateNoteReq {
title: "GPUX 8-Target Architecture".into(),
tags: vec!["rust".into(), "gpui".into(), "webgpu".into()],
},
)?;
println!("Note #{}: {}", res.id, res.summary);
Ok(())
}
在应用构建器中链式绑定并注入 GPUI 视图
通过 App::new().bind(...) 注册的所有服务都会自动注入到 run_with_view 的视图构建上下文中,在桌面、移动端、Web WASM 与小程序中行为完全一致:
rust
App::new()
.title("GPUX Studio")
.size(1120.0, 720.0)
.bind("cluster.ping", |node: String| {
Ok(format!("Node {node} ACK in 0.18ms ({:?})", PlatformKind::current()))
})
.run_with_view(|_window, cx, services| {
cx.new(|_cx| StudioView::new(services))
})