我想使用Webassembly计算一个数组的总和。我的锈代码看起来像这样
use std::os::raw::c_int;
#[no_mangle]
pub extern fn bar(my_array: *const c_int, length: c_int) -> *mut c_int{
let slice = unsafe { slice::from_raw_parts(my_array, length as usize) };
let resp: i32 = slice.iter().sum();
resp as *mut c_int
}
将此锈代码编译为wasm。现在,我在golang中调用此函数。
package main
import (
"encoding/binary"
"encoding/hex"
"fmt"
wasm "github.com/wasmerio/go-ext-wasm/wasmer"
)
const length int32 = 4
func main() {
// Instantiate the module.
wasmbyte, _ := wasm.ReadBytes("test.wasm")
instance, _ := wasm.NewInstance(wasmbyte)
defer instance.Close()
hasmemory := instance.HasMemory()
fmt.Println("it has memory:", (hasmemory))
a := []int32{1, 2, 3, 4}
var i int32
var ptr [length]*int32
for i = 0; i < length; i++ {
ptr[i] = &a[i]
fmt.Printf("Value of a[%d] = %d\n", i, *ptr[i])
// pass int value
// lengths := binary.LittleEndian.Uint32(a)
// fmt.Printf("customLen=%d\n", int32(lengths))
// result := int32(lengths)
allocateResult, err := instance.Exports["bar"](*ptr[i], length)
if err != nil {
fmt.Println("error is here", err)
}
binary.LittleEndian.PutUint32(instance.Memory.Data()[0:4], uint32(length))
inputPointer := allocateResult.ToI32()
// Write the subject into the memory.
memory := instance.Memory.Data()[inputPointer:]
binary.LittleEndian.Uint32(memory)
resp := hex.EncodeToString(memory)
fmt.Println("resp:", resp)
}
}
但是此代码没有给我结果。我的代码的逻辑是计算一个数组的总和。在运行时给数组的值我需要做哪些更改?
谢谢
将数据复制到WebAssembly内存(例如WebAssembly内存地址0):
a := []int32{10, 20, 30, 40}
// Copy data to wasm memory:
bytes := instance.Memory.Data()
for i, v := range a {
binary.LittleEndian.PutUint32(bytes[4*i:], uint32(v))
}
从WebAssembly实例获取bar
导出的函数:
bar := instance.Exports["bar"]
用WebAssembly的内存地址和长度调用导出的函数:
result, err := bar(0, 4)
if err != nil {
panic(err)
}
fmt.Println(result)
代码:
package main
import (
"encoding/binary"
"fmt"
wasm "github.com/wasmerio/go-ext-wasm/wasmer"
)
func main() {
// Instantiate the module.
wasmbyte, err := wasm.ReadBytes("test.wasm")
if err != nil {
panic(err)
}
instance, err := wasm.NewInstance(wasmbyte)
if err != nil {
panic(err)
}
defer instance.Close()
hasmemory := instance.HasMemory()
fmt.Println("it has memory:", hasmemory)
a := []int32{10, 20, 30, 40}
// Copy data to wasm memory:
bytes := instance.Memory.Data()
for i, v := range a {
binary.LittleEndian.PutUint32(bytes[4*i:], uint32(v))
}
bar := instance.Exports["bar"]
result, err := bar(0, 4)
if err != nil {
panic(err)
}
fmt.Println(result)
}
输出:
it has memory: true
100