Skip to content

Commit

Permalink
feat: Implement Module.
Browse files Browse the repository at this point in the history
  • Loading branch information
Hywan committed Sep 18, 2020
1 parent a60fe0c commit a582161
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
2 changes: 1 addition & 1 deletion wasmer/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func newError() *Error {
}

return &Error{
message: C.GoString(errorMessagePointer),
message: C.GoStringN(errorMessagePointer, errorLength),
}
}

Expand Down
35 changes: 27 additions & 8 deletions wasmer/module.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
package wasmer

// #include <wasmer_wasm.h>
//
// // We can't create a `wasm_byte_vec_t` directly in Go otherwise cgo
// // complains with “Go pointer to Go pointer”. The hack consists at
// // creating the `wasm_byte_vec_t` directly in C.
// own wasm_module_t* go_wasm_module_new(wasm_store_t *store, uint8_t *bytes, size_t bytes_length) {
// wasm_byte_vec_t wasm_bytes;
// wasm_bytes.size = bytes_length;
// wasm_bytes.data = (wasm_byte_t*) bytes;
//
// return wasm_module_new(store, &wasm_bytes);
// }
import "C"
import "unsafe"
import (
"runtime"
"unsafe"
)

// A WebAssembly module contains stateless WebAssembly code that has
// already been compiled and can be instantiated multiple times.
Expand All @@ -23,23 +37,28 @@ type Module struct {
}

func NewModule(store *Store, bytes []byte) (*Module, error) {
var bytes_ptr *C.char
var bytesPtr *C.uint8_t

if len(bytes) > 0 {
bytes_ptr = (*C.char)(unsafe.Pointer(&bytes[0]))
bytesPtr = (*C.uint8_t)(unsafe.Pointer(&bytes[0]))
}

var wasm_bytes C.wasm_byte_vec_t
wasm_bytes.size = C.size_t(len(bytes))
wasm_bytes.data = (*C.wasm_byte_t)(bytes_ptr)

module := &Module{
_inner: C.wasm_module_new(store.inner(), &wasm_bytes),
_inner: C.go_wasm_module_new(store.inner(), bytesPtr, C.size_t(len(bytes))),
}

runtime.KeepAlive(bytes)
runtime.SetFinalizer(module, func(module *Module) {
C.wasm_module_delete(module.inner())
})

if module == nil {
return nil, newError()
}

return module, nil
}

func (module *Module) inner() *C.wasm_module_t {
return module._inner
}
1 change: 0 additions & 1 deletion wasmer/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ func NewStore(engine *Engine) *Store {
Engine: engine,
}

runtime.KeepAlive(engine)
runtime.SetFinalizer(store, func(store *Store) {
C.wasm_store_delete(store.inner())
})
Expand Down

0 comments on commit a582161

Please sign in to comment.