Replace Option<T> in ffi

for example

pub extern "C" fn rust_decode(string : Box<CStr>) -> Option<Vec<u8>> {...}

how to convert Option<_> into a FFI-safe type

Well it depends on what is inside your Option. For example, if you have Option<Box<T>>, then that is already FFI safe and equivalent to a pointer to T, with None being null pointer.

The bigger problem is honestly the vector. Vectors are not FFI safe — option or not. In this case, you could create your own VecParts struct and mark it #[repr(C)] for FFI-safety.

pub struct VecParts {
    pub ptr: *mut u8,
    pub len: usize,
    pub cap: usize,

You could use a null pointer and zeros for None here.


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.