MST

星途 面试题库

面试题:Rust中unsafe fn的常见使用场景有哪些

请简要阐述Rust语言里unsafe fn在实际开发中的常见使用场景,并举例说明。
23.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试

常见使用场景

  1. 与外部C代码交互:Rust通过extern块与C代码进行交互,在这种情况下常常需要使用unsafe fn。因为C代码可能不遵循Rust的内存安全规则,例如C语言中的裸指针使用等。
  2. 直接内存操作:当需要直接操作内存,绕过Rust的安全检查机制时。比如手动管理内存的分配和释放,Rust的标准库std::alloc中部分函数会涉及到这种场景。
  3. 调用平台特定的底层函数:不同操作系统有其特定的底层API,这些API可能不满足Rust的安全规范,需要使用unsafe fn来调用。

示例

// 与C代码交互示例
extern "C" {
    fn printf(format: *const i8, ...) -> i32;
}

unsafe fn call_c_printf() {
    let message = b"Hello, world!\x00";
    printf(message.as_ptr() as *const i8);
}

// 直接内存操作示例
use std::alloc::{alloc, dealloc, Layout};
use std::ptr;

unsafe fn custom_allocate(size: usize) -> *mut u8 {
    let layout = Layout::from_size_align(size, 1).expect("Layout from size align failed");
    alloc(layout)
}

unsafe fn custom_deallocate(ptr: *mut u8, size: usize) {
    let layout = Layout::from_size_align(size, 1).expect("Layout from size align failed");
    dealloc(ptr, layout);
}

fn main() {
    unsafe {
        call_c_printf();
        let ptr = custom_allocate(10);
        // 使用ptr进行操作
        custom_deallocate(ptr, 10);
    }
}

在上述代码中,call_c_printf函数通过extern "C"块调用C标准库函数printf,因为涉及到与C语言交互,所以是unsafe fncustom_allocatecustom_deallocate函数则展示了直接内存操作的场景,同样也是unsafe fn