我想在 Go 中使用 WebAssembly 计算数组的总和:
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)
}
}
但是这段代码并没有给我预期的结果。我的代码的逻辑是计算数组的总和。数组的值在运行时给出。
我需要做什么改变?
我的 rust 代码看起来像这样
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 { std::slice::from_raw_parts(my_array, length as usize) };
let resp: i32 = slice.iter().sum();
resp as *mut c_int
}
谢谢
蛊毒传说
相关分类