【CXX】6.2 &str — rust::Str

Rust::Str 公共 API
cpp 复制代码
// rust/cxx.h

class Str final {
public:
  Str() noexcept;
  Str(const Str &) noexcept;
  Str(const String &) noexcept;

  // 如果输入不是 UTF-8,抛出 std::invalid_argument 异常。
  Str(const std::string &);
  Str(const char *);
  Str(const char *, size_t);

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

  explicit operator std::string() const;

  // 注意:没有空终止符。
  const char *data() const noexcept;
  size_t size() const noexcept;
  size_t length() const noexcept;
  bool empty() const noexcept;

  using iterator = const char *;
  using const_iterator = const char *;
  const_iterator begin() const noexcept;
  const_iterator end() const noexcept;
  const_iterator cbegin() const noexcept;
  const_iterator cend() const noexcept;

  bool operator==(const Str &) const noexcept;
  bool operator!=(const Str &) const noexcept;
  bool operator<(const Str &) const noexcept;
  bool operator<=(const Str &) const noexcept;
  bool operator>(const Str &) const noexcept;
  bool operator>=(const Str &) const noexcept;

  void swap(Str &) noexcept;
};

std::ostream &operator<<(std::ostream &, const Str &);

注意事项

请注意,rust::Str 的行为类似于 &str,即它是一个借用!C++ 需要特别注意其生命周期。

再次强调:&str 对应的是 rust::Str。不要尝试将 &str 写成 const rust::Str &。C++ 语言级别的引用无法捕获 &str 的"胖指针"特性。

限制

允许作为函数参数或返回值。目前不支持在共享结构体中使用。&mut str 目前也不支持,但由于其使用场景极为罕见,因此影响不大。

示例

rust 复制代码
// src/main.rs

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        fn r(greeting: &str);
    }

    unsafe extern "C++" {
        include!("example/include/greeting.h");
        fn c(greeting: &str);
    }
}

fn r(greeting: &str) {
    println!("{}", greeting);
}

fn main() {
    ffi::c("hello from Rust");
}
cpp 复制代码
// include/greeting.h

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

void c(rust::Str greeting);

// src/greeting.cc

#include "example/include/greeting.h"
#include <iostream>

void c(rust::Str greeting) {
  std::cout << greeting << std::endl;
  r("hello from C++");
}
相关推荐
笑鸿的学习笔记27 分钟前
qt-C++语法笔记之Stretch与Spacer的关系分析
c++·笔记·qt
hardStudy_h42 分钟前
C++——内联函数与Lambda表达式
开发语言·jvm·c++
ZZZS05161 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
位东风2 小时前
【c++学习记录】状态模式,实现一个登陆功能
c++·学习·状态模式
雷羿 LexChien4 小时前
C++内存泄漏排查
开发语言·c++
嘉小华4 小时前
CMake 完全指南:第一章 - 构建的烦恼 - 为什么需要CMake?
c++
Feliz Da Vida4 小时前
[代码学习] c++ 通过H矩阵快速生成图像对应的mask
c++·学习
无聊的小坏坏5 小时前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode
YOLO大师6 小时前
华为OD机试 2025B卷 - 小明减肥(C++&Python&JAVA&JS&C语言)
c++·python·华为od·华为od机试·华为od2025b卷·华为机试2025b卷·华为od机试2025b卷
看到我,请让我去学习7 小时前
OpenCV编程- (图像基础处理:噪声、滤波、直方图与边缘检测)
c语言·c++·人工智能·opencv·计算机视觉