#CString in repr(C) struct

5 messages · Page 1 of 1 (latest)

errant beacon
#

If it's not an owned string that you need, but simply a borrowed type that's a wrapper around a C style string in memory, you could use https://doc.rust-lang.org/stable/std/ffi/struct.CStr.html which is the non-owning counterpart to CString

It can be constructed through various methods, it's not marked as transparent though so wouldn't try directly transmuting, but you can use the from_ptr method to make one

#

?play

use core::ffi::CStr;

fn main() {
    let memory = b"Hello, World!\0";
    let ptr = memory.as_ptr() as *const i8;
    let c_str = unsafe { CStr::from_ptr(ptr) };
    dbg!(c_str);
}
manic coralBOT
#
     Running `target/debug/playground`
[src/main.rs:7] c_str = "Hello, World!"
errant beacon
#

I'm saying that it's not marked with a repr so it's using default representation which means that the underlying layout is unspecified - they mention this in comments in the source code too actually: https://doc.rust-lang.org/stable/src/core/ffi/c_str.rs.html#88

So yeah unfortunately wouldn't be able to do a std::mem::transmute because of that

#

It doesn't do a copy of the memory if that's what you mean