英文:
How do I write to the memory in wasmer-go?
问题
根据这个在wasmer-go的GitHub上的问题,以前可以使用instance.Memory
,但在较新的版本中似乎已经删除了。我可以使用instance.Exports.GetMemory("mem")
,但这不能让我写入内存。我的问题是:我该如何写入这个内存?
谢谢您的帮助!
只是让您知道:这是为了将字符串传递给一个wasm函数。
英文:
According to this issue on the wasmer-go github, it used to be that you could use instance.Memory
but this appears to be missing from newer versions. I can do instance.Exports.GetMemory("mem")
but this does not allow me to write to it. My question is: how do I write to this memory?
Thank you for any help!
Just so you know: this is to pass strings to a wasm function
答案1
得分: 2
我实现这个功能的方式是通过导出一个分配函数(在AssemblyScript中为__alloc,或者在从Go编译的WASM中为malloc),使用这个导出函数来分配内存并返回起始地址。使用instance.Exports.GetMemory("mem").Data()
来获取内存的字节数组,在从分配函数返回的地址开始,手动将数组中的字节用字符串中的字节进行覆盖。我知道这不是最好的方式,但它是在不需要更改wasmer-go的情况下工作的方式。请记住,不同的模块可能使用不同的utf标准(Go使用8位,AssemblyScript使用16位),我通过一个在实例创建时读取的导出来处理这个问题。
英文:
The way I have made this work is with an exported allocate function (__alloc in AssemblyScript or malloc in WASM compiled from Go), use this exported function to allocate the memory and it returns the starting address. Use instance.Exports.GetMemory("mem").Data()
to get the byte array of the memory, start at the address returned from the allocate function, and just manually overwrite the bytes in the array with the bytes from the string. I know this is not the best way but it is the way that works without needing changes to wasmer-go. Keep in mind different modules may use different utf standards (Go uses 8, AssemblyScript 16), I handle this with an export that is read on instance creation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论