First example of a wasm plugin with wasmer

This commit is contained in:
Fabian Schmidt 2024-01-12 20:08:44 +01:00
commit f75de7e6b7
8 changed files with 1475 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

1388
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

14
Cargo.toml Normal file
View File

@ -0,0 +1,14 @@
[package]
name = "wasmer-plugin"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[workspace]
members = [
"./crates/example-plugin",
"./crates/example-runner",
]

View File

@ -0,0 +1,12 @@
[package]
name = "example-plugin"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[lib]
crate-type = ["cdylib"]

View File

@ -0,0 +1,15 @@
#[no_mangle]
pub fn add(one: i32, two: i32) -> i32 {
one + two
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}

View File

@ -0,0 +1,9 @@
[package]
name = "example-runner"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
wasmer = "4.2.5"

View File

@ -0,0 +1,22 @@
use wasmer::{imports, Instance, Module, Store, Value};
static WASM: &[u8] =
include_bytes!("../../../target/wasm32-unknown-unknown/debug/example_plugin.wasm");
fn main() {
let mut store = Store::default();
let module = Module::new(&store, WASM).expect("failed to load Wasm module");
let import_object = imports! {};
let instance = Instance::new(&mut store, &module, &import_object)
.expect("failed to instantiate Wasm module");
let add = instance
.exports
.get_function("add")
.expect("failed to bind function add");
let three = add
.call(&mut store, &[Value::I32(1), Value::I32(2)])
.expect("failed to execute add");
let three = three.first().unwrap().unwrap_i32();
println!("three: {}", three); // "three: 3"
}

14
src/lib.rs Normal file
View File

@ -0,0 +1,14 @@
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}