如何转换Vec< T>成为C友好的* mut T? [英] How can I convert a Vec<T> into a C-friendly *mut T?

查看:60
本文介绍了如何转换Vec< T>成为C友好的* mut T?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rust库,该库通过FFI将 u8 数组返回给C调用者.客户端处理完该库后,该库还可以处理该数组的删除操作.该库没有状态,因此客户端需要拥有该数组,直到将其传递回该库以进行释放.

I have a Rust library that returns a u8 array to a C caller via FFI. The library also handles dropping the array after the client is done with it. The library has no state, so the client needs to own the array until it is passed back to the library for freeing.

使用 box :: from_raw boxed :: into_raw 会很好,但是我无法弄清楚如何将数组转换为返回类型.

Using box::from_raw and boxed::into_raw would be nice, but I couldn't manage to work out how to convert the array into the return type.

推荐答案

Vec< T> 由3个值描述:

就C数组而言,容量是分配的内存大小,而长度是数组中实际包含的元素数.两者都在计算 T 的数量.通常,您需要将这3个值提供给C代码.

In terms of a C array, the capacity is the size of memory allocated, while the length is the number of elements actually contained in the array. Both are counting in number of T. You normally would need to provide these 3 values to your C code.

如果希望它们相等,则可以使用 .shrink_to_fit() ,以根据分配器尽可能减小其容量.

If you want them to be equals, you can use .shrink_to_fit() on the vector to reduce its capacity as near as its size as possible depending on the allocator.

如果将 Vec< T> 的所有权交还给您的C代码,请不要忘记调用 std :: mem :: forget(v)一旦检索到前面描述的3个值,就可以对其进行处理,以避免其析构函数在函数末尾运行.

If you give back the ownership of the Vec<T> to your C code, don't forget to call std::mem::forget(v) on it once you have retrieved the 3 values described before, to avoid having its destructor running at the end of the function.

然后,您可以使用

Afterwards, you can create back a Vec from these 3 values using from_raw_parts(..) like this:

let v = unsafe { Vec::<T>::from_raw_parts(ptr, length, capacity) };

,并在其析构函数运行时将正确释放内存.请注意,三个值必须正确才能使内存释放正确.对于 Vec< u8> 来说不是很重要,但是 Vec 的析构函数将根据其 length 对其包含的所有数据运行析构函数

and when its destructor will run the memory will be correctly freed. Be careful, the 3 values need to be correct for deallocation of memory to be correct. It's not very important for a Vec<u8>, but the destructor of Vec will run the destructor of all data it contains according to its length.

这篇关于如何转换Vec&lt; T&gt;成为C友好的* mut T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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