FFI - Creating a "&[u8]" from "const char*" Slice

Additionally any attempt to access the string fields of the LibLog structure result in crash.
The Host Application cannot read out even the numeric fields correctly which makes me think that the Rust Structure is not aligned correctly in memory to the C Language conventions and thus incompatible with the Host Application.

LibLog: Log creating ...
LibLog: Log created.
LibLog - Code: [0]
LibLog - Log: Version '1'
LibLog - Log (Length: '218103808 / ex [0]: 'Access violation'

When implementing a log_debug() function I see that the structure is correctly populated:

pub extern "C" fn log_debug(oplog: Option<&LibLog>) {
  if let Some(l) = oplog {println!("LibLog Debug: '{:?}'", l)}

which shows:

LibLog: Debug printing ...
LibLog Debug: 'LibLog { iversion: 2, ierrorcode: 0, iloglength: 13, slogmessage: 0x2653010, ierrorlength: 4, serrormessage: 0x2653600 }'
LibLog: Debug printed.

Your log_debug function takes an Option<&LibLog> (similar to a borrowed const LibLog* in C) and log_free takes a Option<Box<LibLog>> (similar to an owned LibLog* in C), however log_clear takes a &mut Option<&mut LibLog>> which corresponds to a LibLog** in C (notice the double indirection). Is that supposed to be like this or is it a typo?

Yes, you are correct!
the function log_clear()
can be changed to :

log_clear(mut oplog: Option<&mut LibLog>)

but actually this is not my biggest problem.

Rather a meaningful LibLog Structure must expose the report and the error messages generated in Rust.

I changed the log_create() function to contain some content:

pub extern "C" fn log_create() -> Box<LibLog> {
    let vslog = b"log created.\n".to_vec();
    let vserr = b"none".to_vec();
    let iloglen = vslog.len();
    let ierrlen = vserr.len();
    let pslog = unsafe { CString::from_vec_unchecked(vslog).into_raw() as *mut u8 };
    let pserr = unsafe { CString::from_vec_unchecked(vserr).into_raw() as *mut u8 };

    Box::new(LibLog {iversion: 2, ierrorcode: 0
      , slogmessage: pslog, iloglength: iloglen as u32
      , serrormessage: pserr, ierrorlength: ierrlen as u32})

and the log_debug() function shows the structure actually contains the content.

LibLog: Debug printing ...
LibLog Debug: 'LibLog { iversion: 2, ierrorcode: 0, iloglength: 13, slogmessage: 0x137d010, ierrorlength: 4, serrormessage: 0x137d600 }'
LibLog: Debug printed.

but any access outside of Rust does crash or print garbage.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.