*mut u_char to Vec<u8>


Hi there,

I’m getting a *mut u_char from a C function and a data size from another call. I want to transform this into a Vec<u8> but I don’t know how to proceed.

The Vec doc has from_raw_parts but it’s explicitly saying it’s not a good way to transform a C pointer to a Vec.

What is the best/safest way to do that?



You should not create a Vec from a C-allocated buffer because Vec will attempt to free it on drop using Rust’s default allocation which will likely be different from C’s. You can use std::slice::from_raw_parts to get a &mut [u8]. It’s correct as long as you make sure that the buffer is not accessed (read/write) or freed by C while &mut [u8] exists.


Thank you for your help!

Actually, I’ve just realised that I need to copy the data, so if I follow you correctly, I’ll use std::slice::from_raw_parts then clone it?


Yes, but instead of cloning, you should use to_vec to get an owned copy from a slice.


Thank you very much!