cxxfastlogging:用 #[cxx::bridge] 实现零样板安全 C++ 绑定
主线位置:主线 3 第二站(现代 C++ 绑定) —— 对比上一节充斥着
unsafe、CStr::from_ptr和Box::into_raw的cfastlogging,看cxxfastlogging/src/lib.rs如何在 0 行unsafe代码 下完成完整的 C++ 绑定。
为什么有了 cfastlogging 还要单独写 cxxfastlogging?
虽然 C++ 可以直接 #include C 头文件调用 cfastlogging,但 C 接口迫使 C++ 程序员放弃 RAII 智能指针、标准字符串视图(rust::Str / std::string_view)、std::vector 以及 C++ 异常机制。
dtolnay/cxx 的核心思想是:在 Rust 与 C++ 之间定义一套受编译器静态验证的共享类型边界(#[cxx::bridge]),由 cxx-build 在编译期同时生成 Rust 侧的 extern "C" 垫片和 C++ 侧的强类型头文件。
flowchart LR
subgraph RustSide["Rust 侧 (cxxfastlogging/src/lib.rs)"]
R1["pub struct Logging(fastlogging::Logging)"]
R2["pub struct Logger(fastlogging::Logger)"]
R3["pub struct WriterConfig(fastlogging::WriterConfigEnum)"]
end
subgraph Bridge["#[cxx::bridge] pub mod ffi"]
B1["extern 'Rust' { type Logging; type Logger; type WriterConfig; }"]
B2["共享 struct/enum: ExtConfigFfi, ServerConfigInfo, CompressionMethodEnum"]
end
subgraph CppSide["C++ 侧 (生成头文件 + RAII 封装)"]
C1["rust::Box<ffi::Logging>"]
C2["rust::Str / rust::Slice<const uint8_t>"]
C3["Result<T> 自动转为 try / catch (const rust::Error&)"]
end
RustSide --> Bridge --> CppSide
三大核心设计技巧(cxxfastlogging/src/lib.rs)
1. Newtype 包装外部 crate 类型以突破孤儿规则
#[cxx::bridge] 的 extern "Rust" 块要求声明的不透明类型(Opaque Rust Types)必须定义在当前 crate 中。因此 cxxfastlogging/src/lib.rs#L22, L121, L524 定义了三个单字段元组结构体(Newtype):
// cxxfastlogging/src/lib.rs#L22, L121, L524
pub struct WriterConfig(fastlogging::WriterConfigEnum);
pub struct Logging(fastlogging::Logging);
pub struct Logger(fastlogging::Logger);
在 #[cxx::bridge] 内部(lib.rs#L811-L927),直接使用 #[Self = "Logging"] 导出静态工厂函数与成员方法:
// cxxfastlogging/src/lib.rs#L846-L865
extern "Rust" {
type Logging;
#[Self = "Logging"]
fn new_default() -> Result<Box<Logging>>;
#[Self = "Logging"]
fn create(level: u8, domain: &str, configs: Vec<Box<WriterConfig>>) -> Result<Box<Logging>>;
fn apply_config(self: &mut Logging, path: &str) -> Result<()>;
fn shutdown(self: &mut Logging, now: bool) -> Result<()>;
fn add_logger(self: &mut Logging, logger: &mut Logger);
// ...
}
C++ 调用方拿到的是 rust::Box<Logging>,当该 rust::Box 离开 C++ 作用域析构时,会自动调用 Rust 的 Drop(进而触发 fastlogging::Logging::drop 自动 shutdown(false)),从根本上杜绝了 C 绑定中忘记释放或 apply_config 误释放指针的 Bug!
2. 用工厂函数拍平 Rust 带载荷枚举(Tagged Union)
C++ 没有与 Rust enum WriterConfigEnum { Console(ConsoleWriterConfig), File(FileWriterConfig), ... } 内存布局直接对应的原生代数数据类型。cxxfastlogging 的解法非常优雅:
- 将
WriterConfig声明为不透明类型type WriterConfig; - 在
WriterConfig上提供 6 个强类型静态工厂方法:WriterConfig::new_console、new_file、new_client、new_server、new_syslog、new_otel(lib.rs#L24-L118),全部返回Box<WriterConfig>(或Result<Box<WriterConfig>, LoggingError>)。
3. Result<T, LoggingError> 自动桥接为 C++ rust::Error 异常
在 #[cxx::bridge] 中,任何返回 Result<T, E>(只要 E: std::fmt::Display,而 LoggingError 派生了 thiserror::Error)的 Rust 函数,在生成的 C++ 函数签名中都会变成直接返回 T,一旦 Rust 返回 Err(e),cxx 运行时会自动將 e.to_string() 包装为 C++ 的 rust::Error(继承自 std::exception)抛出!
查看 cxxfastlogging/src/lib.rs#L759-L775:对于 fastlogging::WriterTypeEnum(其中 File(String)、Client(String)、Server(String) 带有 String 参数,其余变体无参数),作者是如何将它映射到 #[cxx::bridge] 的?
动脑筋答案
因为 #[cxx::bridge] 中的共享 enum 只支持类似 C 的无载荷枚举(C-style enum),作者将其拆成了**「枚举标签 WriterTypeTag + 附加字符串参数 data: &str」**两个参数(见 enable_type(self: &Logging, tag: WriterTypeTag, data: &str)),再由辅助函数 writer_type_from_tag 在 Rust 侧还原为 fastlogging::WriterTypeEnum。这是在使用 cxx 时处理简单带参枚举的标准范式。
小结
本节展示了 cxxfastlogging 如何用零行 unsafe 实现类型安全、RAII 友好的 C++ 绑定。下一节我们将转向 Python 生态,剖析 pyfastlogging 是如何基于 PyO3 构建高性能 Python 日志扩展并处理 GIL 锁的。

