我可以使用 Box::from_raw 从 Vec::into_boxed_slice 释放内存吗? [英] Can I free memory from Vec::into_boxed_slice using Box::from_raw?

查看:47
本文介绍了我可以使用 Box::from_raw 从 Vec::into_boxed_slice 释放内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到以下用于将字节数组返回给C的代码:

I saw the following code for returning a byte array to C:

#[repr(C)]
struct Buffer {
    data: *mut u8,
    len: usize,
}

extern "C" fn generate_data() -> Buffer {
    let mut buf = vec![0; 512].into_boxed_slice();
    let data = buf.as_mut_ptr();
    let len = buf.len();
    std::mem::forget(buf);
    Buffer { data, len }
}

extern "C" fn free_buf(buf: Buffer) {
    let s = unsafe { std::slice::from_raw_parts_mut(buf.data, buf.len) };
    let s = s.as_mut_ptr();
    unsafe {
        Box::from_raw(s);
    }
}

我注意到 free_buf 函数接受一个 Buffer,而不是一个 *mut u8.这是故意的吗?

I notice that the free_buf function takes a Buffer, instead of a *mut u8. Is this intentional?

free_buf 函数能否简化为:

unsafe extern "C" fn free_buf(ptr: *mut u8) {
    Box::from_raw(ptr);
}

推荐答案

您正确地注意到 C 运行时 free 函数仅将指向要释放的内存区域的指针作为参数.

You are correct to note that the C runtime free function takes only a pointer to the memory region to be freed as an argument.

但是,您不会直接调用它.事实上,Rust 有一层抽象出正在使用的实际内存分配器:std::alloc::GlobalAlloc.

However, you don't call this directly. In fact Rust has a layer that abstracts away the actual memory allocator being used: std::alloc::GlobalAlloc.

提供这样一个抽象的原因是为了让其他分配器可以被使用,实际上它相当容易 换出操作系统提供的默认分配器.

The reason for providing such an abstraction is to allow other allocators to be used, and in fact it is quite easy to swap out the default OS provided allocator.

要求任何分配器跟踪块的长度以允许在不向释放函数提供长度的情况下释放它们将是非常有限的,因此一般的释放函数也需要长度.

It would be quite limiting to require that any allocator keeps track of the length of blocks to allow them to be freed without supplying the length to the deallocation function, so the general deallocation function requires the length as well.

您可能有兴趣知道 C++ 有一个类似的抽象.这个答案提供了更多关于为什么要求应用程序跟踪分配的内存区域的长度的更多讨论而不是堆管理器.

You might be interested to know that C++ has a similar abstraction. This answer provides some more discussion about why it could be preferable to require the application to keep track of the lengths of allocated memory regions rather than the heap manager.

这篇关于我可以使用 Box::from_raw 从 Vec::into_boxed_slice 释放内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆