Skip to content

Cannot create, read and write using a wasm module #55

Closed
@jmcad

Description

@jmcad

I've been trying to create a file and write data to it by using a WebAssembly module written in Rust:

#[no_mangle]
pub fn write() -> Result<(), io::Error> {
    println!("Trying to create a file");
    let mut file = File::create("./foo.txt")?;
    // let mut file = File::open("foo.txt")?;
    println!("I created a file");
    file.write_all(b"Hello, world!")?;
    Ok(())
}

#[no_mangle]
pub extern "C" fn waWrite() -> bool {
    let err = write();
    println!("I am in the waWrite function");
    match err {
        Ok(()) => {
            print!("GOOD");
            return true;
        }
        Err(_e) => {
            print!("GOOD");
            return false;
        }
    }
}

However this does not seem to work at all. Are there any solutions/workarounds for this problem or am I missing something obvious?

Here is my Go code:

func main() {
    // stdout to print WASI text
    dir, err := ioutil.TempDir("", "out")
    check(err)
    defer os.RemoveAll(dir)
    stdoutPath := filepath.Join(dir, "stdout")

    engine := wasmtime.NewEngine()
    store := wasmtime.NewStore(engine)
    linker := wasmtime.NewLinker(store)

    // configure WASI imports to write stdout into a file.
    wasiConfig := wasmtime.NewWasiConfig()
    wasiConfig.SetStdoutFile(stdoutPath)
    err = wasiConfig.PreopenDir(".", ".")
    check(err)

    args := []string{"foo.txt"} // file names
    wasiConfig.SetArgv(args)

    // set the version to the same as in the WAT.
    wasi, err := wasmtime.NewWasiInstance(store, wasiConfig, "wasi_snapshot_preview1")
    check(err)

    // link WASI
    err = linker.DefineWasi(wasi)
    check(err)

    // create the WebAssembly-module
    module, err := wasmtime.NewModuleFromFile(store.Engine, "rust_write.wasm")
    check(err)
    instance, err := linker.Instantiate(module)
    check(err)

    // export functions and memory from the WebAssembly module

    write := instance.GetExport("waWrite").Func()

    res, err := write.Call()
    check(err)
    if res == true {
        println("wrote to file")
    } else {
        println("didn't write to file")
    }

    out, err := ioutil.ReadFile(stdoutPath)
    check(err)
    fmt.Print(string(out))
}

func check(err error) {
    if err != nil {
        panic(err)
    }
}

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