当前位置: 首页 > 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());
}
http://www.dtcms.com/a/68301.html

相关文章:

  • 房屋交易平台设计与实现(代码+数据库+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.所有可能的路径
  • WPF窗口读取、显示、修改、另存excel文件——CAD c#二次开发
  • TEXT()的作用
  • 杨辉三角形(信息学奥赛一本通-2043)
  • C、C++打印地址用%u
  • DeepSeek面试——分词算法
  • 搭建基于flask的web应用框架
  • 源代码防泄漏之反向沙箱篇
  • 射频相关概念
  • 利用余弦相似度在大量文章中找出抄袭的文章
  • Peach配置文件中<Agent>模块的作用及参数解析