我的目标是编写一个Kotlin库,将其编译为WebAssembly并从JS调用其功能。几个小时以来,我尝试着建立一个简单的“hello world”。关于此主题的文档不存在或隐藏得很好。

这是我的kotlin文件:

@Used
public fun hello() {
    println("Hello world!")
}

fun main(args: Array<String>) {
    println("main() function executed!")
}

当我将其编译为WebAssembly时,会得到一个hello.wasm和hello.wasm.js文件。

首先,我尝试使用如下代码来执行该功能:
WebAssembly.instantiateStreaming(fetch('hello.wasm'), importObject)
    .then(obj => obj.instance.exports.hello());

然后,我理解我需要在 importObject 参数中传递来自hello.wasm.js文件的导入。所以我想我需要使用hello.wasm.js文件正确初始化wasm程序。

当我像下面那样加载wasm时,没有出现任何错误,并且执行了 main()函数。
<script wasm="hello.wasm" src="hello.wasm.js"></script>

但是,如何从JavaScript执行 hello()函数呢?我发现的唯一Kotlin wasm示例不是调用特定函数,而是从 main()函数渲染某些内容。

此外,非常感谢与相关文档的任何链接。

更新:
我设法执行了该函数,但我不认为这是正确的方法:
<script wasm="hello.wasm" src="hello.wasm.js"></script>
<script>
WebAssembly.instantiateStreaming(fetch('hello.wasm'), konan_dependencies)
        .then(obj => obj.instance.exports['kfun:hello$$ValueType']());
</script>

问题是,如果我这样做,我的wasm文件将被提取两次。

仅加载没有wasm属性的hello.wasm.js文件会导致以下错误:
Uncaught Error: Could not find the wasm attribute pointing to the WebAssembly binary.
    at Object.konan.moduleEntry (stats.wasm.js:433)
    at stats.wasm.js:532

最佳答案

最近,我本人对此进行了一些研究,据我了解,到目前为止,您的用例尚未得到真正的支持。您要找的实际上是一个库,但是如果您查看Kotlin / Native的documentation,它会指出:

根据我的理解,困难在于如何在Javascript和WebAssembly之间传递数据,因为它仅支持int或通过线性内存的相当round回的方式。

07-24 09:48
查看更多