如何将装箱的切片("Box< [T]>")传递给C函数? [英] How to pass a boxed slice (`Box<[T]>`) to a C function?

查看:78
本文介绍了如何将装箱的切片("Box< [T]>")传递给C函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向C函数公开动态数组". C函数将拥有数据,稍后将调用我的函数以释放数据.因此,它将类似于以下内容:

I want to expose a "dynamic array" to a C function. The C function will own the data and later will call a function of mine to free the data. So it'll look something like the following:

fn get_something(len: *mut usize) -> *mut u8;
fn dealloc_something(data: *mut u8, len: usize);

内部,我有一个Box<[T]>(my_vec.to_boxed_slice()).我可以很容易地得到大小/长度,但是我不知道应该返回哪个指针.如果我将从boxed_slice.as_mut_ptr()返回的指针传递给Box::from_raw(),则应用程序崩溃.但是,如果传递从Box::into_raw返回的指针,则找不到内存布局的保证(指针指向数组的第一个元素,并将在将来的所有Rust版本中继续这样做).

Internally I have a Box<[T]> (my_vec.to_boxed_slice()). I can get the size/length pretty easily, but I don't know which pointer I should return. If I pass the pointer returned from boxed_slice.as_mut_ptr() to Box::from_raw(), the application crashes. However, if I pass the pointer returned from Box::into_raw, I can't find a guarantee of memory layout (the pointer points to the first element of the array and will continue to do so for all future Rust versions).

这里有什么解决方案?

推荐答案

Box::into_raw返回一个指向已分配存储区开头的指针.切片是内存中连续的项目序列.因此,指针指向切片中的第一项.如果Box::into_raw返回了其他任何内容,它将不会真正有用.

Box::into_raw returns a pointer to the beginning of the allocated storage. A slice is a contiguous sequence of items in memory. Therefore, the pointer points to the first item in the slice. If Box::into_raw returned anything else, it wouldn't be really useful.

boxed_slice.as_mut_ptr()Box::into_raw之间的主要区别是Box::into_raw获取盒的所有权但不取消分配它,而boxed_slice.as_mut_ptr()仅返回指针的副本并将Box的所有权保留给您的函数,因此编译器会在返回之前隐式删除它.这意味着,当您使用boxed_slice.as_mut_ptr()时,实际上是在返回指向已释放内存的指针!

The main difference between boxed_slice.as_mut_ptr() and Box::into_raw is that Box::into_raw takes ownership of the box but does not deallocate it, while boxed_slice.as_mut_ptr() just returns a copy of the pointer and leaves ownership of the Box to your function, so the compiler implicitly drops it before returning. This means that when you use boxed_slice.as_mut_ptr(), you are essentially returning a pointer to freed memory!

这篇关于如何将装箱的切片("Box&lt; [T]&gt;")传递给C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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