wasmer-java icon indicating copy to clipboard operation
wasmer-java copied to clipboard

Cannot convert String type into WebAssembly

Open JonathanxD opened this issue 4 years ago • 0 comments

Describe the bug

I have the following code in my Rust project:

#[no_mangle]
#[wasm_bindgen]
pub fn test(str: String) -> String {
    test_internal(json::parse(str.as_str()).unwrap()).into()
}

#[no_mangle]
pub fn test_internal(json_value: JsonValue) -> Message {
    let age: Result<u8, _> = json_value.find("age");
    Message::new(vec![format!("Age {}.", age.unwrap())])
}

I've generated the .wasm with wasm-pack build --release, and in the Java side I have:

// Reads the WebAssembly module as bytes.
byte[] wasmBytes = Files.readAllBytes(wasmFilePath.get());

// Instantiates the WebAssembly module.
Instance instance = new Instance(wasmBytes);

// Calls an exported function, and returns an object array.
ObjectMapper om = new ObjectMapper();
String s = om.writeValueAsString(myObject);

Object[] results = instance.exports.getFunction("test")
        .apply(s);

// Drops an instance object pointer which is stored in Rust.
instance.close();

return (String) results[0];

But when trying to run the code above, it fails with the following exception:

Failed to convert the argument 0nth of `test` into a WebAssembly value.

Doing a bit of investigation, I've found that String conversion is not implemented, only minimal primitive types are.

Steps to reproduce

  1. Create a Rust project with a function that takes a String
  2. Compile with wasm-pack build --release
  3. On the Java side, create a simple project to load the compiled Rust Wasm and calls the function with a String argument.
  4. Try to run the code

Expected behavior

Correctly convert from-to string between Rust Wasm and Java.

Actual behavior

Fails with an exception.

JonathanxD avatar Dec 27 '20 15:12 JonathanxD