echojoys
Return string form rust in Wasm
I’m currently learning the interaction between wasm and elixir. I am writing wasm in rust language, but it can only return the starting position of the address of the string, which is *const u8. I can’t get the length. What is the solution? Thanks again.
Thanks! ![]()
Most Liked Responses
tessi
Hey @echojoys ,
I want to follow up on the topic of “safe” string returns through multi-value returns from WASM. I implemented this feature here and expect support for multi-value returns to land very soon in wasmex.
After the MR landed, you can have Rust code that returns a string pointer and length from the same function call:
#[no_mangle]
pub fn to_string(a: i32) -> (i32, i32) {
let str = a.to_string();
(str.as_ptr() as i32, str.len() as i32)
}
from Elixir you can call that function like any old function:
{:ok, [pointer, length]} = Wasmex.call_function(instance, :to_string, [54321])
{:ok, memory} = Wasmex.memory(instance)
assert Wasmex.Memory.read_string(store, memory, pointer, length) == "54321"
(the code snippets are an extract from Wasmex tests, have a look at those wasmex_test.exs tests to see more examples)
I hope this helps! ![]()
cheers,
tessi
echojoys
Hey Tessi,
I cannot express how appreciative I am for your detailed and insightful response. Your solution is ingenious, and it’s exactly what I was looking for.
The code snippets you provided have clarified my understanding significantly. It’s enlightening to see how Rust can return a string pointer and length from the same function call, and how Elixir can subsequently call that function. Moreover, I must commend your patience and effort in helping me resolve this issue.
Once again, thank you so much for your time and assistance. I look forward to learning more from your expertise in the future.
Best regards








