天天看点

使用CXX进行Rust和C++的安全互操作

作者:不秃头程序员
使用CXX进行Rust和C++的安全互操作

CXX是一个提供Rust和C++之间安全调用机制的库,能够避免使用bindgen或cbindgen生成不安全的C风格绑定时可能出现的各种问题。本文将展示如何配置和使用CXX库,探讨其主要特性,并提供一些示例代码。

CXX简介

CXX库提供了一种机制,可以从Rust调用C++代码,也可以从C++调用Rust代码。我们通过在一个Rust模块中定义两边的FFI边界,然后CXX进行静态分析,确保类型和函数签名的正确性。CXX会生成相应的extern "C"签名,来保证在构建过程中验证无误。生成的FFI桥接在运行时几乎没有开销,不会涉及复制、序列化、内存分配或运行时检查。

安装与配置

首先,我们需要在Rust项目的Cargo.toml文件中添加CXX库作为依赖项:

[dependencies]
cxx = "1.0"

[build-dependencies]
cxx-build = "1.0"           

然后,我们需要创建一个构建脚本build.rs,用于运行CXX的C++代码生成器,并编译生成的C++代码:

// build.rs

fn main() {
    cxx_build::bridge("src/main.rs")  // 返回一个 cc::Build 实例
        .file("src/demo.cc")
        .std("c++11")
        .compile("cxxbridge-demo");

    println!("cargo:rerun-if-changed=src/main.rs");
    println!("cargo:rerun-if-changed=src/demo.cc");
    println!("cargo:rerun-if-changed=include/demo.h");
}           

示例代码

我们通过一个具体的例子来展示如何使用CXX实现Rust和C++的互操作。假设我们有一个现有的C++客户端用于一个大文件存储服务,我们希望在Rust应用中利用这个客户端。

1. 定义FFI边界

在Rust代码中,我们定义两个静态外部块,一个用于Rust,一个用于C++。

// src/main.rs

#[cxx::bridge]
mod ffi {
    #[derive(Debug)]
    struct BlobMetadata {
        size: usize,
        tags: Vec<String>,
    }

    extern "Rust" {
        type MultiBuf;

        fn next_chunk(buf: &mut MultiBuf) -> &[u8];
    }

    unsafe extern "C++" {
        include!("demo/include/blobstore.h");

        type BlobstoreClient;

        fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
        fn put(&self, parts: &mut MultiBuf) -> u64;
        fn tag(&self, blobid: u64, tag: &str);
        fn metadata(&self, blobid: u64) -> BlobMetadata;
    }
}           

2. 在Rust中实现方法

我们为Rust部分实现必要的方法。例如MultiBuf结构体和next_chunk函数:

// src/main.rs

pub struct MultiBuf {
    chunks: Vec<Vec<u8>>,
    current: usize,
}

impl MultiBuf {
    pub fn new(chunks: Vec<Vec<u8>>) -> Self {
        MultiBuf { chunks, current: 0 }
    }
}

fn next_chunk(buf: &mut MultiBuf) -> &[u8] {
    let chunk = &buf.chunks[buf.current];
    buf.current = (buf.current + 1) % buf.chunks.len();
    chunk
}           

3. 在C++中实现方法

接下来我们需要在C++中实现相应的函数。在demo/include/blobstore.h文件中定义C++接口:

// demo/include/blobstore.h

#pragma once
#include <cxx.h>

struct BlobMetadata {
    size_t size;
    rust::Vec<rust::String> tags;
};

struct BlobstoreClient;
std::unique_ptr<BlobstoreClient> new_blobstore_client();
uint64_t put(BlobstoreClient& self, rust::Box<MultiBuf>& parts);
void tag(BlobstoreClient& self, uint64_t blobid, rust::Str tag);
BlobMetadata metadata(const BlobstoreClient& self, uint64_t blobid);           

然后在demo/src/blobstore.cc中实现这些方法:

// demo/src/blobstore.cc

#include "demo/include/blobstore.h"
#include <memory>
#include <vector>

struct MultiBuf {
    std::vector<std::vector<uint8_t>> chunks;
    size_t current;

    MultiBuf(std::vector<std::vector<uint8_t>>&& chunks)
        : chunks(std::move(chunks)), current(0) {}
};

struct BlobstoreClient {
    std::vector<std::shared_ptr<MultiBuf>> buffers;
};

std::unique_ptr<BlobstoreClient> new_blobstore_client() {
    return std::make_unique<BlobstoreClient>();
}

uint64_t put(BlobstoreClient& self, rust::Box<MultiBuf>& parts) {
    self.buffers.push_back(std::shared_ptr<MultiBuf>(parts.release()));
    return self.buffers.size() - 1;
}

void tag(BlobstoreClient& self, uint64_t blobid, rust::Str tag) {
    // Implementation of tagging (not essential for this example)
}

BlobMetadata metadata(const BlobstoreClient& self, uint64_t blobid) {
    BlobMetadata metadata;
    metadata.size = self.buffers[blobid]->chunks.size();
    // Populate tags as needed
    return metadata;
}           

4. 主程序

最后,我们可以在Rust主程序中使用这些方法:

// src/main.rs

fn main() {
    let client = ffi::new_blobstore_client();
    let mut buf = MultiBuf::new(vec![vec![1, 2, 3], vec![4, 5, 6]]);
    
    let id = client.put(&mut buf);
    let meta = client.metadata(id);
    println!("Blob id: {}, size: {}", id, meta.size);
}           

安全与性能

CXX库的设计在保证安全性的同时也注重性能。例如,通过静态分析防止将不应该按值传递的类型从C++传递到Rust。此外,CXX会在必要时插入零开销的变通方法,从而让结构体按值传递时保持ABI兼容性。

总结

CXX提供了一种安全简便的机制,用于在Rust和C++之间进行互操作。本文展示了如何配置CXX库,定义FFI边界,并在Rust和C++中分别实现相应的方法。通过使用CXX,我们可以在保证安全性的同时实现高效的跨语言调用。

继续阅读