【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++");
}
相关推荐
王老师青少年编程6 小时前
2026年6月GESP真题及题解(C++一级):交税
c++·题解·真题·gesp·一级·2026年6月·交税
花褪残红青杏小7 小时前
Rust图像处理第12节-图片翻转与旋转:坐标重映射几何变换
rust·webassembly·图形学
疋瓞10 小时前
python和C++对比(1)_数据类型和数据结构
数据结构·c++·python
C语言小火车11 小时前
C++ 堆排序深度精讲:基于完全二叉树的选择排序进化,最坏情况 O(n log n) 的稳定王者
开发语言·c++·算法·排序算法·堆排序
ALex_zry11 小时前
C++26 std::complex 结构化绑定详解:auto [re, im] = c
c语言·开发语言·c++
_olone13 小时前
Luogu P2704 [NOI2001] 炮兵阵地
c++·算法·状压dp
c2385613 小时前
互斥锁高频面试题全解:从基础概念到底层实现,一文通关
java·c++·面试·职场和发展
nianniannnn13 小时前
c++复习自存--继承
开发语言·c++
旖-旎14 小时前
《LeetCode 746 使用最小花费爬楼梯 || LeetCode 91 解码方法》
c++·算法·leetcode·动态规划
ALex_zry15 小时前
C++26 constexpr 异常详解:编译期也能 throw/catch
java·jvm·c++