How to return a Result type in cdylib?


I have a cdylib project that generates a dynamic link library to be used in another rust project. When I tried to return a Result type in the export interface, programs just crashed. What I should do if I want to pass enums? Thanks

By the way, I found that Option is ok.

As implied by the name, cdylib produces a dynamic library conforming to C ABI. Unfortunately, C ABI does not support Result type.

One way to handle enum's through the extern api is to convert them to integers first. See the num crate FromPrimitive and related derive. num::traits::FromPrimitive - Rust

Not sure about option (maybe none will produce null?), but a found a few discussions related to that:

There's also some discussion related to of having a stable Rust ABI (rlib?), see Define a Rust ABI · Issue #600 · rust-lang/rfcs · GitHub

I think it's about std::thread::Result, that has Err confined to Box<dyn Any + Send + 'static>, I think maybe the dynamic trait caused the crash?

You can't deallocate memory from the dylib outside of the dylib

So, as mentioned above, returning -> Result<…, Box<dyn …>> does not work across cdylib boundaries.

To answer the OP question, "how to …", the shortest answer is that you use the types defined in ::abi_stable::std_types::*:

use ::abi_stable::std_types::*; // Naming convention: `RTypeName`.

#[no_mangle] pub extern "C"
fn example () -> RResult<i32, RBoxError>
    … /* sprinkle `.into()` calls here and there as necessary */

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.