【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");
}
相关推荐
OSwich1 小时前
【虚幻C++笔记】枚举UENUM、结构体USTRUCT
c++·笔记·虚幻
techdashen1 小时前
微软为何选择用Go而非Rust重写TypeScript
microsoft·golang·rust
周Echo周2 小时前
6、STL中list的使用方法
数据结构·c++·windows·后端·算法·链表·list
Antonio9158 小时前
【设计模式】原型模式
c++·设计模式·原型模式
17´10 小时前
Qt从入门到入土(十) -数据库操作--SQLITE
数据库·c++·qt·sqlite
阿拉保10 小时前
C++复试笔记(四)
java·c++·笔记
郭源潮110 小时前
《 线程池项目:线程池背景知识与整体架构梳理》
c++·线程池·c++11·c++17
Dream it possible!11 小时前
CCF CSP 第30次(2023.09)(1_坐标变换_C++)(先输入再计算;边输入边计算)
c++·算法·csp