examples(allocation): free memory after unmarshalling a result from the guest (#1368)
Signed-off-by: Luca Burgazzoli <lburgazzoli@gmail.com>
This commit is contained in:
20
examples/allocation/tinygo/testdata/greet.go
vendored
20
examples/allocation/tinygo/testdata/greet.go
vendored
@@ -6,6 +6,9 @@ import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// #include <stdlib.h>
|
||||
import "C"
|
||||
|
||||
// main is required for TinyGo to compile to Wasm.
|
||||
func main() {}
|
||||
|
||||
@@ -70,10 +73,17 @@ func ptrToString(ptr uint32, size uint32) string {
|
||||
}
|
||||
|
||||
// stringToPtr returns a pointer and size pair for the given string in a way
|
||||
// compatible with WebAssembly numeric types.
|
||||
// compatible with WebAssembly numeric types. The pointer is not automatically
|
||||
// managed by tinygo but must be freed by the host.
|
||||
func stringToPtr(s string) (uint32, uint32) {
|
||||
buf := []byte(s)
|
||||
ptr := &buf[0]
|
||||
unsafePtr := uintptr(unsafe.Pointer(ptr))
|
||||
return uint32(unsafePtr), uint32(len(buf))
|
||||
if len(s) == 0 {
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
size := C.ulong(len(s))
|
||||
ptr := unsafe.Pointer(C.malloc(size))
|
||||
|
||||
copy(unsafe.Slice((*byte)(ptr), size), []byte(s))
|
||||
|
||||
return uint32(uintptr(ptr)), uint32(len(s))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user