Best practices for "Error reporting from Rust to C"?

Hi I'm building embeddable Rust library for integrating it as a C library for other programming languages.
I'm stuck in designing error handling process from Rust code to C.
For example I need to return some structure from Rust code, and also I need to report an error, in C/C++ I can write something like this.

SomeType * someFunc() {
   // do something smart
   if (err) return NULL; // this is horrible, but we have to tell there is an error
}

How can I send an error from exported Rust function to FFI interface where I don't have standard Option type of Rust, and also can't return a NULL?

Wanted to check is there a classic way to do this, or I need to hack around defined struct and add some error handling fields?
Thanks

1 Like

This is a link to an example, one of the more ambitious C APIs implemented in Rust that I know of:

https://github.com/gfx-rs/portability/blob/master/libportability-gfx/src/lib.rs#L680

Edit: I’m on a tablet ATM, writing is slow. I hope the link can serve as inspiration at least. If possible try to let the user of the library do all memory allocation, or do it exclusively inside the library, try not to mix it.

4 Likes