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

【CXX】6.2 Rust::Str 公共 API

// 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 目前也不支持,但由于其使用场景极为罕见,因此影响不大。

示例

// 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");
}
// 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++");
}

相关文章:

  • MySQL中的`JSON_EXTRACT`函数
  • Anthropic 平台升级,解锁 Claude3.7Sonnet 与 prompt 创作新玩法
  • SPI驱动(六) -- SPI_OLED上机实验(使用spidev)
  • 梯度计算中常用的矩阵微积分公式
  • 计算机网络----主要内容简介
  • Qwen2.5-7B-Instruct进行自我认知微调
  • HTTP 黑科技
  • 为什么会有结构体?
  • 《几何原本》命题I.25
  • PCIE接口
  • spring 和JVM之间关系
  • Go学习笔记
  • 【RAG】检索后排序 提高回答精度
  • 初识Linux
  • 一周学会Flask3 Python Web开发-SQLAlchemy定义数据库模型
  • 【Linux篇】调试器-gdb/cgdb使用
  • Redis- 切片集群
  • Linux驱动学习之平台总线设备树驱动模型
  • vue3 使用sass变量
  • 基于STC89C52的温度检测系统(DS18B20)
  • 镇江个人网站建设/免费发布推广信息的平台有哪些
  • 简历上作品展示网站链接怎么做/培训行业seo整站优化
  • java网站开发经验/短视频优化
  • 做网站建网站/帮人推广的平台
  • 网站发布与推广计划/今日腾讯新闻最新消息
  • 我爱建站免费空间/友情链接地址