Interacting with data from FFI in Rust

submited by
Style Pass
2021-08-06 19:00:08

If you ever need to call a function from another language, you'll have to use FFI (Foreign Function Interface) and very likely handle pointers. To help you with that, here are some tips.

The NonNull type is very important: whenever interacting with pointers, it makes the nullability check automatic. In the following codes, we assume the alignment to be correct. For example:

But at least you can't have a null pointer anymore because you forgot to check it. It also improves your code readability and you get some niche optimization (Option<NonNull<T>> is the same size as *mut T).

Let's say you have a void* that you got from reading a file containing i32s (the read function doesn't care of the type of the array, it only reads up to the number of bytes you asked it). You could iterate through it in C style like this:

This is not great because it forces you to keep the size around and to handle the offset yourself. A much better alternative is to use slice::from_raw_parts:

Leave a Comment