Skip to content

Question about strings and structs and wasmtime API #891

Closed
@eminence

Description

@eminence

I've got the following rust code:

pub struct Person {
    name: String,
    age: u8,
}

#[no_mangle]
pub fn get_age(p: &Person) -> u8 {
    p.age
}

#[no_mangle]
pub fn greet(name: &str) -> String {
    "hello there:".to_string()
}

that I'm compiling to the wasm32-unknown-unknown target:

cargo +nightly build --target wasm32-unknown-unknown --release

To my surprise, this compiled happily. Since strings and structs are not types that webassembly knows about, I was surprised to even see a successful compilation. My understanding was that in order to deal with these types you either have to use wasm-bindgen, or interface types.

I'm not using wasm-bindgen, and I'm not using interface types (since when I look at the output, I don't see any of the interface types custom sections).

So my first question is: how is this actually working in the first place?

I'm not fluent in reading wasm, but when I looked at the generated code (attached in full at the bottom, but quoted in brief here), it all looked quite reasonable:

    (func $get_age (type 5) (param i32) (result i32) 
      local.get 0
      i32.load8_u offset=12)

This seems reasonable: The parameter looks to be an offset into wasm linear memory to some structure that expects the 'age' field to be at offset 12 from the start of the structure.

My next question: how do I call this from the wasmtime API? How to I construct an instance of my Person struct and put it into the right memory? How do I know how to layout my struct?

A similar question applies to greet:

  (func $greet (type 4) (param i32 i32 i32)

It looks like string types are transferred using 3 i32s (how do I create those from a string), but where's the return type?

Thanks!

plugin.wat.txt

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