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

【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.kler.cn/a/585755.html

相关文章:

  • 渗透测试工具之Empire Framework
  • 交互式调度算法学不会?————一文学懂(RR(时间片轮转调度算法),优先级调度算法,多级反馈队列调度算法)保姆式解析
  • DPU的架构:模块化与可扩展性
  • MFC控件按钮的使用
  • 破局企业数据泄露风险:安当TDE透明加密重塑文件服务器安全防线
  • Flutter+Rust Android, IOS移动端适配通用流程及依赖库处理(Openssl, Curl等)
  • 百度百科更新!树莓集团宜宾项目的深远影响与意义
  • leetcode hot100贪心
  • LeetCode hot 100—滑动窗口最大值
  • win32汇编环境,对话框程序中创建托盘示例一
  • PyTorch 系列教程:探索自然语言处理应用
  • 基于RWA 与 AI-Agent 协同的企业数字化生态构建
  • Go语言环境搭建并执行第一个Go程序
  • X86 RouterOS 7.18 设置笔记十:上海电信IPTV使用msd_lite实现组播转单拨
  • C++小课堂——friend友元
  • 基础知识《DICT协议》
  • 路由器配置命令
  • 完善机器人:让 DeepSeek 生成 API 接口,并在网页上调用
  • MySQL 的 innodb_buffer_pool_size 参数配置指南
  • [AI QA] strace | 探索 a.out