【CXX】6.8 Vec<T> — rust::Vec<T>

发布于:2025-03-15 ⋅ 阅读:(15) ⋅ 点赞:(0)

rust::Vec

公共API:
// rust/cxx.h

template <typename T>
class Vec final {
public:
  using value_type = T;

  Vec() noexcept;
  Vec(std::initializer_list<T>);
  Vec(const Vec &);
  Vec(Vec &&) noexcept;
  ~Vec() noexcept;

  Vec &operator=(Vec &&) & noexcept;
  Vec &operator=(const Vec &) &;

  size_t size() const noexcept;
  bool empty() const noexcept;
  const T *data() const noexcept;
  T *data() noexcept;
  size_t capacity() const noexcept;

  const T &operator[](size_t n) const noexcept;
  const T &at(size_t n) const;
  const T &front() const;
  const T &back() const;

  T &operator[](size_t n) noexcept;
  T &at(size_t n);
  T &front();
  T &back();

  void reserve(size_t new_cap);
  void push_back(const T &value);
  void push_back(T &&value);
  template <typename... Args>
  void emplace_back(Args &&...args);
  void truncate(size_t len);
  void clear();

  class iterator;
  iterator begin() noexcept;
  iterator end() noexcept;

  class const_iterator;
  const_iterator begin() const noexcept;
  const_iterator end() const noexcept;
  const_iterator cbegin() const noexcept;
  const_iterator cend() const noexcept;

  void swap(Vec &) noexcept;
};
限制:

Vec 不支持 T 为不透明的 C++ 类型。对于在语言边界上处理不透明 C++ 类型的集合,应改用 CxxVector(C++ 中的 std::vector)。

示例:
// src/main.rs

#[cxx::bridge]
mod ffi {
    struct Shared {
        v: u32,
    }

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

        fn f(elements: Vec<Shared>);
    }
}

fn main() {
    let shared = |v| ffi::Shared { v };
    let elements = vec![shared(3), shared(2), shared(1)];
    ffi::f(elements);
}
// include/example.h

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

void f(rust::Vec<Shared> elements);

// src/example.cc

#include "example/include/example.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>

void f(rust::Vec<Shared> v) {
  for (auto shared : v) {
    std::cout << shared.v << std::endl;
  }

  // 使用 STL 算法将元素复制到 C++ 的 std::vector 中。
  std::vector<Shared> stdv;
  std::copy(v.begin(), v.end(), std::back_inserter(stdv));
  assert(v.size() == stdv.size());
}

网站公告

今日签到

点亮在社区的每一天
去签到