当前位置: 首页 > news >正文

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

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());
}

相关文章:

  • 房屋交易平台设计与实现(代码+数据库+LW)
  • ECA注意力机制改进思路
  • 第三章-PHP流程控制语句
  • Linux 运行级别
  • 带宽管理配置实验
  • 【Azure 架构师学习笔记】- Azure Databricks (21) --费用相关
  • 进程管理:前后台切换
  • 3U VPX 国产化板卡FT6678+V7 690T
  • 格式化输出备忘
  • css的显示模式
  • fs的proxy_media模式失效
  • 网络安全 与 加密算法
  • ngx_command_t
  • Spring Cloud LoadBalancer 原理与实践
  • 网络安全——SpringBoot配置文件明文加密
  • 三相逆变器不控整流场景简要分析
  • 【6】拓扑排序学习笔记
  • 什么是 Redis
  • 【QT】】qcustomplot的使用
  • leecode797.所有可能的路径
  • 内蒙古赤峰市城建集团董事长孙广通拟任旗县区党委书记
  • 大学2025丨北大教授陈平原:当卷不过AI时,何处是归途
  • 民间打拐志愿者上官正义遭人身安全威胁,杭州公安:已立案
  • 一周文化讲座|“我的生命不过是温柔的疯狂”
  • 既是工具又是食物,可食用机器人开启舌尖上的新科技
  • 外企聊营商|特雷通集团:税务服务“及时雨”