mmmrrr
Rustler return and pass reference from Rust to Elixir and back to Rust
The starting point: The Erlang ODBC client has a “bug” where it only allows 4096 bytes to be returned per cell. The Rust odbc client has no such limitations.
The reasoning: I’d like to avoid Rust for the web layer, since that would result in a lot of training for my peers.
The (probably insane) idea: Use Rustler to provide a custom “odbc driver” that can be used from Elixir.
The problem: I’d need to store the established connections somewhere in Elixir in order to pass them to the query functions and I’m not quite sure if this would work with Rustlers unsafe functions.
So the questions are:
- How do I return a Rust reference to a “thing” to Elixir in order to pass it again to Rust later on?
- Is there anything that disqualifies this idea categorically (except from the fact that it is probably a huge effort)
Marked As Solved
mickel8
@mmmrrr @dimitarvp I probably solved my issue. It turned out I should use rustler::init! and rustler::resource! macros. Here is full code. It compiles so that’s something
use rustler::resource::ResourceArc;
use rustler::{Env, Term, NifStruct};
rustler::atoms! {
ok,
error
}
rustler::init!("PineSSL", [add], load=load);
#[derive(NifStruct)]
#[module = "MyStruct"]
pub struct MyStruct {
pub a: i64
}
fn load(env: Env, _info: Term) -> bool {
rustler::resource!(MyStruct, env);
true
}
#[rustler::nif]
fn add(a: i64, b: i64) -> ResourceArc<MyStruct> {
ResourceArc::new(MyStruct{a: a+b})
}
macro rustler::resource! implements ResourceTypeProvider trait for MyStruct and in rustler::init! I can invoke my function load which then invokes rustler::resource!.
Also Liked
tessi
@hauleth 's suggestion is on point.
If you need an example, you could look at wasmex (GitHub - tessi/wasmex: Execute WebAssembly from Elixir · GitHub).
For example, a WebAssembly module instance has an elixir representation with an attached Rust struct. It is passed down in some methods defined here to the Rust-layer.
In Rust-land, we override the Wasmex::Native module with the respective rust functions taking that rust-struct reference.
In instance.rs you can see how to attach structs (instance in my case) to elixir objects (new_from_bytes) and how to extract structs from elixir objects (e.g. function_export_exists).
dimitarvp
Here’s something that should work with minimal changes:
use rustler::resource::ResourceArc;
use rustler::{Encoder, Env, Term};
rustler::atoms! { error, ok, }
type MyRustReturnType = YOUR_RUST_TYPE_HERE;
enum MyResult {
Success(ResourceArc<MyRustReturnType>),
Failure(String),
}
impl<'a> Encoder for MyResult {
fn encode<'b>(&self, env: Env<'b>) -> Term<'b> {
match self {
MyResult::Success(arc) => (ok(), arc).encode(env),
MyResult::Failure(msg) => (error(), msg).encode(env),
}
}
}
// or DirtyCpu, or just remove the "schedule" option and leave the clause to be simply: `#[rustler::nif]`
#[rustler::nif(schedule = "DirtyIo")]
fn something() -> MyResult {
match function_that_can_fail() {
Ok(rust_object) => MyResult::Success(ResourceArc::(rust_object)),
Err(e) => MyResult::Failure(e.to_string()),
}
}
You might need to remove the lifetime qualifiers though, can’t remember why my code needed them now. Using Rustler’s ResourceArc is crucial here; thanks to it you will receive the Rust object wrapped in a nice Erlang Reference which in the case of this function you’ll see in your iex console like so (in the case of success):
{:ok, #Reference<0.679634982.4171759622.38993>}
…or in case of failure:
{:error, "error message from Rust here"}
Then on the Elixir side you should take care to have the same something() function that Rustler will wrap and pass through to Rust (this is covered in Rustler’s guide). That’s basically it. Poke me if you need more help, Rustler could be tricky and it seems the maintainers don’t have time for it for a long time now.
hauleth
Use NIF resource for that, you probably will need to dig in Rustler docs how to do that in Rust.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








