【发布时间】:2019-06-05 21:14:08
【问题描述】:
我的目标是编写一个 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
【问题讨论】:
-
我最终用 Rust 编写了我的库,工具和文档要好得多,一切都按预期工作。
标签: javascript kotlin webassembly kotlin-native kotlin-js-interop