bytecodealliance / cargo-wasi

A lightweight Cargo subcommand to build Rust code for the `wasm32-wasi` target
https://bytecodealliance.github.io/cargo-wasi/
Apache License 2.0
444 stars 29 forks source link

Compilation failed ? #136

Closed orangeC23 closed 1 year ago

orangeC23 commented 1 year ago

Steps to reproduce

(1) cargo new testfile (2) cd testfile Modify the main.rs :


use std::fs::File;
use std::os::unix::io::AsRawFd;

fn main() {
    let file = File::open("./hello.txt").expect("Can not open.");
    let file_descriptor = file.as_raw_fd();
    println!("File descriptor {}", file_descriptor);

}

And create file hello.txt.

(3) execute cargo run , it prints:

File descriptor 3

(4) However, when execute 'cargo build --target wasm32-wasi', it prints image

pchickey commented 1 year ago

This issue has to do with Rust std, not wasmtime. The std::os::unix module is not available when targeting wasi, because wasi is not a unix. There is no equivalent of AsRawFd for that target.

What are your needs for AsRawFd under wasi?

sunfishcode commented 1 year ago

Rust std recently add a new feature, the std::os::fd module, which abstracts over unix and wasi, and contains an AsRawFd which works on both WASI and Unix.

So if you write your program like this:

use std::fs::File;
use std::os::fd::AsRawFd;

fn main() {
    let file = File::open("./hello.txt").expect("Can not open.");
    let file_descriptor = file.as_raw_fd();
    println!("File descriptor {}", file_descriptor);

}

It compiles under both Unix and WASI.

orangeC23 commented 1 year ago

Thanks a lot ! Now it works !