Move all examples to a top-level directory (#1286)

* Move all examples to a top-level directory

This commit moves all API examples (Rust and C) to a top-level
`examples` directory. This is intended to make it more discoverable and
conventional as to where examples are located. Additionally all examples
are now available in both Rust and C to see how to execute the example
in the language you're familiar with. The intention is that as more
languages are supported we'd add more languages as examples here too.

Each example is also accompanied by either a `*.wat` file which is
parsed as input, or a Rust project in a `wasm` folder which is compiled
as input.

A simple driver crate was also added to `crates/misc` which executes all
the examples on CI, ensuring the C and Rust examples all execute
successfully.
This commit is contained in:
Alex Crichton
2020-03-11 15:37:24 -05:00
committed by GitHub
parent d44384da8a
commit 3c51d3adb8
33 changed files with 1131 additions and 528 deletions

26
examples/gcd.rs Normal file
View File

@@ -0,0 +1,26 @@
//! Example of instantiating of the WebAssembly module and invoking its exported
//! function.
// You can execute this example with `cargo run --example gcd`
use anyhow::Result;
use wasmtime::*;
fn main() -> Result<()> {
// Load our WebAssembly (parsed WAT in our case), and then load it into a
// `Module` which is attached to a `Store` cache. After we've got that we
// can instantiate it.
let store = Store::default();
let module = Module::from_file(&store, "examples/gcd.wat")?;
let instance = Instance::new(&module, &[])?;
// Invoke `gcd` export
let gcd = instance
.get_export("gcd")
.and_then(|e| e.func())
.ok_or(anyhow::format_err!("failed to find `gcd` function export"))?
.get2::<i32, i32, i32>()?;
println!("gcd(6, 27) = {}", gcd(6, 27)?);
Ok(())
}