diff --git a/examples/allocation/tinygo/testdata/greet.go b/examples/allocation/tinygo/testdata/greet.go index 2eb717d5652..5c7468978c8 100644 --- a/examples/allocation/tinygo/testdata/greet.go +++ b/examples/allocation/tinygo/testdata/greet.go @@ -6,6 +6,7 @@ import "C" import ( "fmt" "reflect" + "runtime" "unsafe" ) @@ -21,6 +22,7 @@ func greet(name string) { func log(message string) { ptr, size := stringToPtr(message) _log(ptr, size) + runtime.KeepAlive(message) } // _log is a WebAssembly import which prints a string (linear memory offset, @@ -72,13 +74,13 @@ 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. +// stringToPtr returns a pointer and size pair to the underlying bytes of the given +// string in a way compatible with WebAssembly numeric types. Since Go strings are +// immutable, the pointer returned by stringToPtr must not be modified. func stringToPtr(s string) (uint32, uint32) { - buf := []byte(s) - ptr := &buf[0] + ptr := unsafe.StringData(s) unsafePtr := uintptr(unsafe.Pointer(ptr)) - return uint32(unsafePtr), uint32(len(buf)) + return uint32(unsafePtr), uint32(len(s)) } // stringToLeakedPtr returns a pointer and size pair for the given string in a way diff --git a/examples/allocation/tinygo/testdata/greet.wasm b/examples/allocation/tinygo/testdata/greet.wasm index 6a7fa978690..cc2fe35ddac 100755 Binary files a/examples/allocation/tinygo/testdata/greet.wasm and b/examples/allocation/tinygo/testdata/greet.wasm differ