Stream: general

Topic: How to pass array from python to wasm


view this post on Zulip Moore (Nov 22 2024 at 11:28):

pub extern "C" fn sample_fn(a: &[f32; 3]) -> f32 {
    let mut sum: f32 = a[0] + a[1];
    return sum;
}

then I'm calling with:

from cffi import FFI
ffi = FFI()

elems = ffi.new("float [3]")
elems[0] = 0.1
elems[1] = 0.2
elems[2] = 22.0

print(wasm_mod.sample_fn(
    int(ffi.cast('int32_t', elems))
))

the fn signature requires an i32 to be passed which I suppose is the array pointer. when I pass int32_t I get memory fault, and I can't cast it to type float * as python won't accept it.

view this post on Zulip Lann Martin (Nov 22 2024 at 14:37):

Does your actual code have the #[no_mangle] attribute on the rust function?

view this post on Zulip Moore (Nov 22 2024 at 14:51):

Yes. It works fine when I use two floats. It's only the float arrays which I can't pass.

view this post on Zulip Joel Dice (Nov 22 2024 at 14:58):

A Wasm guest can't access host memory, so passing a host pointer to the guest won't work. You'll need some way to allocate guest memory from the host (e.g. another, malloc-style function export), which the host can use to allocate space for a copy of the array, then copy the content from the host array to the guest array (being careful to convert the guest pointer to a host pointer by adding the linear memory base pointer to it), then pass the guest pointer to sample_fn.


Last updated: Dec 23 2024 at 12:05 UTC