parity-wasm/examples/interpret.rs

44 lines
2.0 KiB
Rust
Raw Normal View History

// In this example we execute a contract funciton exported as "_call"
2017-05-10 17:04:09 +03:00
extern crate parity_wasm;
use std::env::args;
2017-08-01 14:44:33 +03:00
use parity_wasm::{interpreter, ModuleInstanceInterface};
2017-05-10 17:04:09 +03:00
fn main() {
let args: Vec<_> = args().collect();
2017-05-10 17:06:09 +03:00
if args.len() != 3 {
2017-05-10 17:04:09 +03:00
println!("Usage: {} <wasm file> <arg>", args[0]);
println!(" wasm file should contain exported `_call` function with single I32 argument");
return;
}
// Intrepreter initialization.
// parity_wasm::ProgramInstance can be parameterized with a custom User error to be returned from native modules
// parity_wasm::DefaultProgramInstance parametrize ProgramInstance with a pre-defined "DummyUserError"
// Initializes a default "env" module also.
2017-08-01 14:44:33 +03:00
let program = parity_wasm::DefaultProgramInstance::with_env_params(
2017-05-30 17:24:22 +03:00
interpreter::EnvParams {
total_stack: 128*1024,
total_memory: 2*1024*1024,
allow_memory_growth: false,
}
).expect("Failed to load program");
// Here we load module using dedicated for this purpose
// `deserialize_file` function (which works only with modules)
2017-05-10 17:04:09 +03:00
let module = parity_wasm::deserialize_file(&args[1]).expect("Failed to load module");
// Intialize deserialized module. It adds module into It expects 3 parameters:
// - a name for the module
// - a module declaration
// - "main" module doesn't import native module(s) this is why we don't need to provide external native modules here
// This test shows how to implement native module https://github.com/NikVolf/parity-wasm/blob/master/src/interpreter/tests/basics.rs#L197
2017-06-13 12:01:59 +03:00
let module = program.add_module("main", module, None).expect("Failed to initialize module");
// The argument should be parsable as a valid integer
2017-05-10 17:06:09 +03:00
let argument: i32 = args[2].parse().expect("Integer argument required");
2017-08-29 20:02:48 +03:00
// "_call" export of function to be executed with an i32 argument and prints the result of execution
2017-05-18 15:08:55 +03:00
println!("Result: {:?}", module.execute_export("_call", vec![parity_wasm::RuntimeValue::I32(argument)].into()));
2017-05-10 17:04:09 +03:00
}