I have the following code which run as expected on Perl
use Wasm::Wasmtime;
my $store = Wasm::Wasmtime::Store->new;
my $module = Wasm::Wasmtime::Module->new( $store->engine, wat => q{
(module
(func (export "add") (param i32 i32) (result i32)
local.get 0
local.get 1
i32.add)
)
});
my $instance = Wasm::Wasmtime::Instance->new($module, $store);
my $add = $instance->exports->add;
print $add->call(1,2), "\n"; # 3
but i have binary wasm file how can i point to it instead of WAT text , inside the ->new any idea?
CodePudding user response:
As Keith alluded in his comment, the trick is to just give a file
argument rather than a wat
one to Wasm::Wasmtime::Module->new
. This snippet turns your provided WAT into a disk .wasm
file, then loads and runs it. If you have the .wasm
file already, then obviously you don't need to use the little wat2file
function shown:
use Wasm::Wasmtime;
my $filename = 'myfile.wasm';
# this is just to make your WAT text into a disk WASM file, making this self-contained
# don't use it if you already have a .wasm file already!
my $wat = q{
(module
(func (export "add") (param i32 i32) (result i32)
local.get 0
local.get 1
i32.add)
)
};
wat2file($filename, $wat);
my $store = Wasm::Wasmtime::Store->new;
my $module = Wasm::Wasmtime::Module->new($store->engine, file => $filename);
my $instance = Wasm::Wasmtime::Instance->new($module, $store);
my $add = $instance->exports->add;
print $add->call(1,2), "\n"; # 3
sub wat2file {
my ($filename, $wat) = @_;
require Wasm::Wasmtime::Wat2Wasm;
open my $fh, '>', $filename;
print $fh Wasm::Wasmtime::Wat2Wasm::wat2wasm($wat);
}