Skip to content

WebAssembly.instantiateStreaming returning undefined for string function #11689

@GJZwiers

Description

@GJZwiers

I'm trying to fetch a WebAssembly module from the server with the new WebAssembly.instantiateStreaming, which works fine for Rust functions with number arguments but returns undefined when a function with string arguments is called.

The Rust code:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    return format!("Hello, {}!", name);
}

#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

It's compiled with wasm-pack build --target web and then served like this:

const server = Deno.listen({ port: 8080 });

for await (const conn of server) {
  handle(conn);
}

async function handle(conn: Deno.Conn) {
  const httpConn = Deno.serveHttp(conn);
  
  for await (const requestEvent of httpConn) {
    try {
      await requestEvent.respondWith(new Response(
        await Deno.readFile("./pkg/wasm_bg.wasm"), {
          status: 200,
          headers: {
            "content-type": "application/wasm",
          },
        },
      ),
    );
    } catch (e) {
      console.log(e);
    }
  }
}

Then I run the following code client-side with Deno after the server is up and running:

const wasm = await WebAssembly.instantiateStreaming(fetch("http://localhost:8080"));

const greet = wasm.instance.exports.greet as (name: string) => string;

const add = wasm.instance.exports.add as (a: number, b: number) => number;

console.log(greet("World"));

console.log(add(1, 2));

add works as expected but greet returns undefined instead of Hello, World!. I though it might have something to do with using format! So I've tried to return String::from(name) as well with the same undefined result. Is this not a recommended way to compile WebAssembly for Deno or is it perhaps not possible to convert the Rust mutable String type to a JavaScript string in this way? If you need more information I'd be happy to provide it.

My deno --version:

deno 1.13.0 (release, x86_64-unknown-linux-gnu) <-- Ubuntu WSL 2
v8 9.3.345.11
typescript 4.3.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions