天天看點

使用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,我們可以在保證安全性的同時實作高效的跨語言調用。

繼續閱讀