getditto/safer_ffi

Q: how to return a Rust side heap allocated object to C's main()? any example code?

Opened this issue · 3 comments

mw66 commented

Hi,

I'm a Rust newbie, and just tried the mid_point example on the README:

#116

I noticed that the function mid_point return the whole struct Point_t (as scalar value) back to C's main(), which means that after Rust side's mid_point is returned, Rust does not hold any memory for that object.

However, I'm wondering how to return a Rust side heap allocated object to C's main()? e.g. I'm trying to use Rust's DashMap from C's main(), in such case, the Rust side always need to hold the allocated DashMap in heap memory for further insert and get operations (while the caller main() is in C).

https://docs.rs/dashmap/latest/dashmap/struct.DashMap.html

Sorry for the newbie question if the answer is obvious.

Can you show me some code example, or even add examples/dashmap? :-) or if you show me some code snippets, I will do the PR.

Thanks!

Heh, I guess this is what I wanted to document over https://getditto.github.io/safer_ffi/example-hashmap/_.html, but I never got around doing it 😅

Most of the necessary documentation / examples for this pattern is located around the "opaque struct pattern" documentation, since that feature is the keystone to making all this work:

mw66 commented

Thanks for the link and info.

BTW, before I saw you reply here, I found another way to do this, using once_cell::sync::Lazy;

https://github.com/yilabs/librust_interop/blob/main/rust/src/synced.rs#L27

Basically, for each Rust container e.g. DashMap in this case, which is to be exported to C's main, using a Vec to hold all the containers of this type, and return its vec index (u64) as the the handle to the C side, and each time the C side can call method of the container via this handle; and the call is protected by a RwLock depends on the exact method being called.

As said, I'm a Rust newbie, if you see any problem of this approach please let me know. Thanks.

Hello @danielhenrymantilla,

I have found this library, and it's great! Is there any way to pass some BTreeMap/HashMap over FFI using this library? A minimal example would be great! Also, I only need to return the HashMap from a function.

I really appreciate any help you can provide.