繁体   English   中英

我如何在 Perl 的 Wasm::Wasmtime 中使用二进制 WASM 文件?

[英]How can I use a binary WASM file in Perl's Wasm::Wasmtime?

我有以下代码在 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

但是我有二进制 wasm 文件我怎么能指向它而不是 WAT 文本,在 ->new 里面有什么想法吗?

正如 Keith 在他的评论中提到的,诀窍是只给Wasm::Wasmtime::Module->new一个file参数而不是wat参数。 此代码段将您提供的 WAT 转换为磁盘.wasm文件,然后加载并运行它。 如果您已经有了.wasm文件,那么显然您不需要使用所示的小wat2file function:

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM