Giter Site home page Giter Site logo

wasmer-rust-example's Introduction

Rust Embedder App Example

NOTE: Please see the Wasmer Rust Integration documentation for an up-to-date example of user the Wasmer Rust Integration / Embedding.

This repo showcases how to use the wasmer-runtime from Rust, based on the blogpost: https://medium.com/wasmer/executing-webassembly-in-your-rust-application-d5cd32e8ce46

See src/main.rs for the example implementation.

The wasm-sample-app directory contains an example rust wasm app to run in the embedder app.

Requirements

  • Rust target wasm32-unknown-unknown - install using rustup target add wasm32-unknown-unknown

Running

# Building the wasm-sample-app
cd wasm-sample-app && cargo build --release && cd ..

# Running the wasm sample from Rust
cargo run

wasmer-rust-example's People

Contributors

bjfish avatar frank-dspeed avatar lachlansneff avatar markmccaskey avatar syrusakbary avatar torch2424 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wasmer-rust-example's Issues

Failure to build on Windows

On the latest stable version of Rust I have encountered the following error when trying to build the example.

   Compiling wasmer-runtime-core v0.1.2
error[E0432]: unresolved import `self::memory`
 --> C:\Users\Donet\.cargo\registry\src\github.com-1ecc6299db9ec823\wasmer-runtime-core-0.1.2\src\sys\windows\mod.rs:1:15
  |
1 | pub use self::memory::{Memory, Protect};
  |               ^^^^^^ could not find `memory` in `self`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0432`.
error: Could not compile `wasmer-runtime-core`.

Invoking async functions

I have a library in which I am trying to invoke async functions belonging to yet another library of mine. Is there a way to achieve this using the wasmer API?

have not found wasm file

  • Hello~
  • I have a problem. I have not get a "wasm" file when i run this: rustup target add wasm32-unknown-unknown and cargo build --target wasm32-unknown-unknown .The dir of target is like this:
target/wasm32-unknown-unknown/debug/
├── build
├── deps
│   ├── libwasmer_plugin_example-5c131292408204bf.rmeta
│   ├── libwasmer_plugin_example-b451bca680263c78.rlib
│   ├── wasmer_plugin_example-5c131292408204bf.d
│   └── wasmer_plugin_example-b451bca680263c78.d
├── examples
├── incremen
  • My os is 18~18.04.1-Ubuntu
  • rust version is rustc 1.34.0 (91856ed52 2019-04-10),cargo version is cargo 1.34.0 (6789d8a0a 2019-04-01)

Using wasmer with context

Let's say I want to call WASM code using some context. For example, I have a struct Boo and I want to use "self.a" as part of the WASM execution. Is it possible to do?

Here is the modified example:

extern crate wasmer_runtime;

use std::str;

use wasmer_runtime::{
    imports,
    instantiate,
    error,
    Ctx,
};

// Make sure that the compiled wasm-sample-app is accessible at this path.
static WASM: &'static [u8] = include_bytes!("../wasm-sample-app/target/wasm32-unknown-unknown/release/wasm_sample_app.wasm");

fn main() -> error::Result<()> {
    // Let's define the import object used to import our function
    // into our webassembly sample application.
    //
    // We've defined a macro that makes it super easy.
    //
    // The signature tells the runtime what the signature (the parameter
    // and return types) of the function we're defining here is.
    // The allowed types are `i32`, `u32`, `i64`, `u64`,
    // `f32`, and `f64`.
    //
    // Make sure to check this carefully!
    let boo = Boo{ a: 42 };

    boo.run()?;

    Ok(())
}

struct Boo {
    a: u32,
}

impl Boo {

    fn run(&self) -> error::Result<()> {
        let import_object = imports! {
            // Define the "env" namespace that was implicitly used
            // by our sample application.
            "env" => {
                // name         // func    // signature
                "print_str" => self.print_str<[u32, u32] -> []>,
            },
        };


        // Compile our webassembly into an `Instance`.
        let mut instance = instantiate(WASM, import_object)?;

        // Call our exported function!
        instance.call("hello_wasm", &[])?;

        Ok(())
    }

    // Let's define our "print_str" function.
    //
    // The declaration must start with "extern" or "extern "C"".
    extern fn print_str(&self, ptr: u32, len: u32, ctx: &mut Ctx) {
        // Get a slice that maps to the memory currently used by the webassembly
        // instance.
        //
        // Webassembly only supports a single memory for now,
        // but in the near future, it'll support multiple.
        //
        // Therefore, we don't assume you always just want to access first
        // memory and force you to specify the first memory.
        let memory = ctx.memory(0);

        // Get a subslice that corresponds to the memory used by the string.
        let str_slice = &memory[ptr as usize..(ptr + len) as usize];

        // Convert the subslice to a `&str`.
        let string = str::from_utf8(str_slice).unwrap();

        // Print it!
        println!("{} (and a = {})", string, self.a);
    }
}

Writing data to Wasmer VM

How in wasmer-runtime to write data in memory of VM and to read them in wasm Rust? I know how to do this in JS, but I did not find the API in the wasmer-runtime to transfer the data. In the above code, I tried to read the data on stupid.

main.rs

...
static TEST_STR: &'static str = "Test string";
...
instance.call("str_wasm", &[Value::I32(TEST_STR.as_ptr() as i32), Value::I32(TEST_STR.len() as i32)])?;
...

lib.rs

...
#[no_mangle]
pub extern fn str_wasm(ptr: *mut u8, len: usize) {
    let slice: &[u8] = unsafe { slice::from_raw_parts(ptr, len) };
    let string = str::from_utf8(slice).unwrap();
    unsafe {
        print_str(string.as_ptr(), string.len());
    }
}
...

Well, it is clear that this is too simple. Here is the error: Error: CallError (Runtime (OutOfBoundsAccess {memory: MemoryIndex (0), addr: None}))

ABI generation using wasmer

How can we generate ABI using wasmer for rust lang code? Is it possible now? If yes what are the steps to generate ABI?

This blog https://medium.com/wasmer/webassembly-cloudabi-b573047fd0a9 shows that wasmer is going to support CloudABI. Is it done?

Can wasmer support any rust code or is there any simantics to write code in wasmer environment?

And can we use wasmer ( the ABI generated from wasmer) in blockchain?

When I run command
wasmer run wasm-sample-app/target/wasm32-unknown-unknown/release/wasm_sample_app.wasm
i'm getting
"Can\'t instantiate module: LinkError([ImportNotFound { namespace: \"env\", name: \"print_str\" }])"
what is is issue? how to fix it?

wasmer/wasi with rust lib project

I was able to get my project to run as a binary project but it failed to run as a library project. does wasmer/wasi only support rust binary projects and not library projects. The application wrote file to a specific folder allowed by the preopen_dirs function.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.