【CXX】6.5 Box<T> — rust::Box<T>

rust::Box公共 API:

cpp 复制代码
// rust/cxx.h

template <typename T>
class Box final {
public:
  using element_type = T;
  using const_pointer =
      typename std::add_pointer<typename std::add_const<T>::type>::type;
  using pointer = typename std::add_pointer<T>::type;

  Box(Box &&) noexcept;
  ~Box() noexcept;

  explicit Box(const T &);
  explicit Box(T &&);

  Box &operator=(Box &&) & noexcept;

  const T *operator->() const noexcept;
  const T &operator*() const noexcept;
  T *operator->() noexcept;
  T &operator*() noexcept;

  template <typename... Fields>
  static Box in_place(Fields &&...);

  void swap(Box &) noexcept;

  // 重要:要求 `raw` 必须来自 `into_raw` 调用。不要
  // 传递来自 `new` 或其他来源的指针。
  static Box from_raw(T *) noexcept;

  T *into_raw() noexcept;
};

限制:

Box 不支持 T 为不透明的 C++ 类型。对于在语言边界传递不透明 C++ 类型的所有权,应使用 UniquePtr 或 SharedPtr。

如果 T 是不透明的 Rust 类型,则要求该 Rust 类型为 Sized,即在编译时已知大小。未来可能会引入对动态大小的不透明 Rust 类型的支持。

示例:

以下程序使用 Box 将某些不透明的 Rust 状态的所有权传递给 C++,然后再传递回 Rust 回调函数。这是实现 FFI 异步函数的有用模式。

rust 复制代码
// src/main.rs

use std::io::Write;

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        type File;
    }

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

        fn f(
            callback: fn(Box<File>, fst: &str, snd: &str),
            out: Box<File>,
        );
    }
}

pub struct File(std::fs::File);

fn main() {
    let out = std::fs::File::create("example.log").unwrap();

    ffi::f(
        |mut out, fst, snd| { let _ = write!(out.0, "{}{}\n", fst, snd); },
        Box::new(File(out)),
    );
}
cpp 复制代码
// include/example.h

#pragma once
#include "example/src/main.rs.h"
#include "rust/cxx.h"

void f(rust::Fn<void(rust::Box<File>, rust::Str, rust::Str)> callback,
       rust::Box<File> out);

// include/example.cc

#include "example/include/example.h"

void f(rust::Fn<void(rust::Box<File>, rust::Str, rust::Str)> callback,
       rust::Box<File> out) {
  callback(std::move(out), "fearless", "concurrency");
}
相关推荐
bruce541102 小时前
深入理解 Rust Axum:两种依赖注入模式的实践与对比(二)
rust
risc-v@cn4 小时前
【在ubuntu下使用vscode打开c++的make项目及编译调试】
c++·vscode·ubuntu
让我们一起加油好吗4 小时前
【C++】多态(详解)
c++·visualstudio·多态·虚函数
草莓熊Lotso4 小时前
【C++】--函数参数传递:传值与传引用的深度解析
c语言·开发语言·c++·其他·算法
zylyehuo5 小时前
C++提高编程
c++
scx201310045 小时前
20250822 组题总结
c++·算法
困鲲鲲6 小时前
CMake2: CMakeLists.txt的常用命令
c++·cmake·常用命令
云边有个稻草人6 小时前
【C++】第二十五节—C++11 (上) | 详解列表初始化+右值引用和移动语义
c++·c++11·右值引用·移动语义·列表初始化·移动构造·移动赋值
源代码•宸7 小时前
网络流量分析——基础知识(二)(Tcpdump 基础知识)
运维·开发语言·网络·c++·经验分享·tcpdump
johnZhangqi14 小时前
深圳大学-计算机信息管理课程实验 C++ 自考模拟题
java·开发语言·c++