Using Rust inside a Crystal program

Am I to understand that LLVM optimizes and compiles Crystal+Rust code into a single binary, without using FFI? Do we get a performance hit this way? How it performs?

What about Crystal’s garbage collector? Does it scan for Rust’s heap allocated variables?

Wanna understand how they co-exist.

The details depend on which specific mechanism is used.
But the most common method would probably be to expose the Rust library in a C-compatible interface and build it into a library. Then we can define bindings for that in Crystal and call into the library. This is not specific to Rust but works for any language that can produce C-compatible libraries (technically, even Crystal itself).

Crystal can link C functions directly, so there’s no FFI or any other performance overhead.

Memory management must be arranged manually. This is usually part of the lib interface. For example, some libraries require to be passed sufficiently sized memory buffers which are completely handled by the caller. Others return pointers to their allocated memory and ask the caller to free them.

1 Like

Right you can see how I link to a Rust library here: tantivy.cr/src/lib_tantivy.cr at master - bendangelo/tantivy.cr - Codeberg.org

The method I used is Crystal will free the memory itself, and Rust will ignore any clean up on it’s side. This made things a lot easier.

1 Like