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

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