parity-wasm/examples/interpret.rs

39 lines
1.8 KiB
Rust
Raw Permalink 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;
2018-01-11 15:16:30 +03:00
use parity_wasm::interpreter::{ModuleInstance, NopExternals, RuntimeValue, ImportsBuilder};
2018-01-10 18:42:28 +03:00
use parity_wasm::validation::validate_module;
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;
}
2017-08-30 13:54:26 +03:00
// 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");
2017-08-30 13:54:26 +03:00
2018-01-10 18:42:28 +03:00
let validated_module = validate_module(module).expect("Failed to validate module");
2018-01-08 15:10:50 +03:00
// Intialize deserialized module. It adds module into It expects 3 parameters:
2017-12-13 19:11:25 +01:00
// - 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
2018-01-11 15:16:30 +03:00
let main = ModuleInstance::new(&validated_module, &ImportsBuilder::default())
2018-01-10 18:42:28 +03:00
.expect("Failed to instantiate module")
.run_start(&mut NopExternals)
.expect("Failed to run start function in 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
2018-01-10 18:42:28 +03:00
println!("Result: {:?}", main.invoke_export("_call", &[RuntimeValue::I32(argument)], &mut NopExternals));
2017-05-10 17:04:09 +03:00
}