I have a Rust dynamic library which is intended to be called from any language. The arguments to the exported function are two char *
pointers to memory and two lengths for each piece of memory.
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. I'm then using bincode::deserialize
on the slices to use them as Rust objects. Is there any safer option to deal with incoming raw pointers to 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'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.
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
This doesn't seem correct. No memory should be copied to create a slice. A Rust slice is effectively just a pair of (pointer, length)
— the same things that you are passing in separately. I'd expect those each to be register-sized, so calling memcpy
would be overkill.
Using the resulting slice could possibly involve copying the data, but that's not due to from_raw_parts
anymore.