From 4d057f44ca0c80f6edc6d64a3d604d0ecaf60370 Mon Sep 17 00:00:00 2001 From: "Federico G. Schwindt" Date: Thu, 18 Mar 2021 15:56:13 +0000 Subject: [PATCH] Add an Instance method to lookup an exported func (#69) This avoid having to check both the return from `.GetExport()` and `.Func()`, and follows after `instance.get_func()` from the Rust API. --- instance.go | 12 ++++++++++++ instance_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/instance.go b/instance.go index 4d5abd168dcf..c8b105c09bf2 100644 --- a/instance.go +++ b/instance.go @@ -135,6 +135,18 @@ func (i *Instance) GetExport(name string) *Extern { return i.exports[name] } +// GetFunc attemps to find a function on this instance by `name`. +// +// May return `nil` if this instance has no function named `name`, +// it is not a function, etc. +func (i *Instance) GetFunc(name string) *Func { + f := i.GetExport(name) + if f == nil { + return nil + } + return f.Func() +} + func (i *Instance) populateExports() { exports := i.Exports() for j, ty := range i.Type().Exports() { diff --git a/instance_test.go b/instance_test.go index 16bb5308f324..6684c7a23498 100644 --- a/instance_test.go +++ b/instance_test.go @@ -115,3 +115,43 @@ func TestInstanceBad(t *testing.T) { panic("expected an error") } } + +func TestInstanceGetFunc(t *testing.T) { + wasm, err := Wat2Wasm(` + (module + (func (export "f") (nop)) + (global (export "g") i32 (i32.const 0)) + ) + `) + if err != nil { + panic(err) + } + store := NewStore(NewEngine()) + module, err := NewModule(store.Engine, wasm) + if err != nil { + panic(err) + } + instance, err := NewInstance(store, module, []*Extern{}) + if err != nil { + panic(err) + } + + f := instance.GetFunc("f") + if f == nil { + panic("expected a function") + } + _, err = f.Call() + if err != nil { + panic(err) + } + + f = instance.GetFunc("g") + if f != nil { + panic("expected an error") + } + + f = instance.GetFunc("f2") + if f != nil { + panic("expected an error") + } +}