[Solved] Converting UTF-8 char* from C

I am trying to convert a string coming via the FFI from the libraptor library.

The data is stored in this struct

http://librdf.org/raptor/api/raptor2-section-triples.html#raptor-term-literal-value

As far as I can tell, this is UTF-8 encoded and contains the length – that is it’s not null-terminated. Ironically, this seems to be causing me grief in conversion. I’ve tried moving it using CString, but it routinely gives garbage or just crashes out.

I guess I need to convert this to an u8 slice and then use from_utf8_unchecked. But I am not sure how this works from a raw pointer.

I am a relative newcomer to Rust and know C worse.

Found the answer immediately after posting

std::str::from_utf8(std::slice::from_raw_parts
                                (literal.string, literal.string_len as usize))
             .unwrap()
             .to_string()

Left the question in case anyone else finds it!

1 Like