简体   繁体   English

是否有替代原始指针的不安全 slice::from_raw_parts 的安全替代方法?

[英]Is there a safe alternative to replace the unsafe slice::from_raw_parts for raw pointers?

I have a Rust dynamic library which is intended to be called from any language.我有一个 Rust 动态库,可以从任何语言调用。 The arguments to the exported function are two char * pointers to memory and two lengths for each piece of memory. arguments 到导出的 function 是两个指向 memory 的char *指针和每个 ZCD691B4957F098CDE236 的两个长度

The problem is that from_raw_parts reduces to a memcpy and can segfault in a variety of dangerous ways if for example the lengths are wrong.问题是from_raw_parts减少到一个 memcpy 并且如果例如长度错误,可能会以各种危险的方式出现段错误。 I'm then using bincode::deserialize on the slices to use them as Rust objects.然后我在切片上使用bincode::deserialize将它们用作 Rust 对象。 Is there any safer option to deal with incoming raw pointers to memory?有没有更安全的选项来处理指向 memory 的传入原始指针?

No.不。

What you are asking doesn't make sense.你问的没有意义。 To some level, the entire reason that Rust the language exists is because raw pointers are inherently dangerous.在某种程度上, Rust 语言存在的全部原因是因为原始指针本质上是危险的。 Rust's references (and their related lifetimes) are a structured way of performing compile-time checks to ensure that a pointer is valid and safe to use. Rust 的引用(及其相关的生命周期)是一种执行编译时检查以确保指针有效且可以安全使用的结构化方式。

Once you start using raw pointers, the compiler can no longer help you with those pointers and it's now up to you to ensure that safety is guaranteed.一旦您开始使用原始指针,编译器就无法再帮助您处理这些指针,现在由来确保安全性得到保证。


from_raw_parts reduces to a memcpy from_raw_parts为 memcpy

This doesn't seem correct.这似乎不正确。 No memory should be copied to create a slice.不应复制 memory 以创建切片。 A Rust slice is effectively just a pair of (pointer, length) — the same things that you are passing in separately. Rust 切片实际上只是一对(pointer, length) ——与您分别传入的相同的东西。 I'd expect those each to be register-sized, so calling memcpy would be overkill.我希望它们每个都是寄存器大小的,所以调用memcpy将是矫枉过正。

Using the resulting slice could possibly involve copying the data, but that's not due to from_raw_parts anymore.使用生成的切片可能涉及复制数据,但这不再是由于from_raw_parts的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM