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

Rust_2025:阶段1:day7.2unsafe , 链接相关

unsafe

  1. 是一个作用域块
  2. 提示编译器不用对作用域块内的操作进行检查
unsafe fn modify_by_address(address: usize) {// TODO: Fill your safety notice of the code block below to match your// code's behavior and the contract of this function. You may use the// comment of the test below as your format reference.unsafe {//todo!("Your code goes here")let ptr = address as *mut u32 ;*ptr = 0xAABBCCDD;}
}#[cfg(test)]
mod tests {use super::*;#[test]fn test_success() {let mut t: u32 = 0x12345678;// SAFETY: The address is guaranteed to be valid and contains// a unique reference to a `u32` local variable.unsafe { modify_by_address(&mut t as *mut u32 as usize) };assert!(t == 0xAABBCCDD);}
}
  1. 当对一个引用转换为*mut u32时,这时候的值就是地址了。
  2. 对地址解引用就可以直接操作内存。

将指针转换为Box

unsafe fn raw_pointer_to_box(ptr: *mut Foo) -> Box<Foo> {// SAFETY: The `ptr` contains an owned box of `Foo` by contract. We// simply reconstruct the box from that pointer.let mut ret: Box<Foo> = unsafe { let mut ret = Box::from_raw(ptr);ret.b = Some("hello".to_owned());ret};//todo!("The rest of the code goes here")ret
}
  • 实现了由不安全到安全的转变

链接 ,全局符号

extern "Rust" {fn my_demo_function(a: u32) -> u32;#[link_name = "my_demo_function"]fn my_demo_function_alias(a: u32) -> u32;
}mod Foo {// No `extern` equals `extern "Rust"`.#[no_mangle]fn my_demo_function(a: u32) -> u32 {a}
}#[cfg(test)]
mod tests {use super::*;#[test]fn test_success() {// The externally imported functions are UNSAFE by default// because of untrusted source of other languages. You may// wrap them in safe Rust APIs to ease the burden of callers.//// SAFETY: We know those functions are aliases of a safe// Rust function.unsafe {my_demo_function(123);my_demo_function_alias(456);}}
}
  1. extern是全局符号,声明里面的符号是全局符号
  2. 但这时候函数的符号并不是自己的名字,而是加了一些修饰。在定义函数的地方添加#[no_mangle]就可以成功链接
  3. 在全局符号声明中使用#[link_name = “my_demo_function”]可以给符号改名。
http://www.dtcms.com/a/394342.html

相关文章:

  • 【论文速递】2025年第15周(Apr-06-12)(Robotics/Embodied AI/LLM)
  • 设计模式简单说明:责任链与规则树
  • 自动备份脚本 mysql_hourly_backup.sh
  • SuperGLUE:自然语言理解的挑战与进步
  • 线程安全的单例模式、自旋锁,以及读者写者问题
  • U盘长期插在电脑上的影响
  • Windows 系统部署 PaddleOCR —— 基于 EPGF 架构
  • 数据一致性指的是什么?如何实现数据一致性?
  • 初识消息队列的世界
  • Python快速入门专业版(三十八):Python字典:键值对结构的增删改查与进阶用法
  • SpringCloudOAuth2+JWT:微服务统⼀认证方案
  • LeetCode 分类刷题:2517. 礼盒的最大甜蜜度
  • 深度学习优化器进阶:从SGD到AdamW,不同优化器的适用场景
  • C++ 之 【C++的IO流】
  • truffle学习笔记
  • 现代循环神经网络
  • vlc播放NV12原始视频数据
  • ThinkPHP8学习篇(七):数据库(三)
  • 链家租房数据爬虫与可视化项目 Python Scrapy+Django+Vue 租房数据分析可视化 机器学习 预测算法 聚类算法✅
  • MQTT协议知识点总结
  • C++ 类和对象·其一
  • TypeScript里的类型声明文件
  • 【LeetCode - 每日1题】设计电影租借系统
  • Java进阶教程,全面剖析Java多线程编程,线程安全,笔记12
  • DCC-GARCH模型与代码实现
  • 实验3掌握 Java 如何使用修饰符,方法中参数的传递,类的继承性以及类的多态性
  • 【本地持久化】功能-总结
  • 深入浅出现代FPU浮点乘法器设计
  • LinkedHashMap 访问顺序模式
  • 破解K个最近点问题的深度思考与通用解法