javascript - 如何从 JavaScript 执行 Kotlin WebAssembly 函数?

标签 javascript kotlin webassembly kotlin-native kotlin-js-interop

我的目标是编写一个 Kotlin 库,将其编译为 WebAssembly 并从 JS 调用它的函数。几个小时后,我试图让一个简单的 hello world 工作。关于这个主题的文档要么不存在,要么隐藏得很好。

这是我的 kotlin 文件:

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

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

当我将它编译成 WebAssembly 时,我得到一个 hello.wasmhello.wasm.js 文件。

首先我尝试使用类似的东西来执行该功能:

WebAssembly.instantiateStreaming(fetch('hello.wasm'), importObject)
    .then(obj => obj.instance.exports.hello());

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

当我像下面这样加载我的 wasm 时,我没有收到任何错误,并且执行了 ma​​in() 函数。

<script wasm="hello.wasm" src="hello.wasm.js"></script>

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

非常感谢任何指向相关文档的链接。


更新: 我设法执行了该功能,但我不认为这是正确的方法:

<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

最佳答案

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

The following binary kinds are supported (note that not all the kinds are available for all native platforms):

[...]

sharedLib - a shared native library - all native targets except wasm32

staticLib - a static native library - all native targets except wasm32

据我了解,困难在于 Javascript 和 WebAssembly 之间的数据传递,因为它只支持整数或通过线性内存的迂回方式。

关于javascript - 如何从 JavaScript 执行 Kotlin WebAssembly 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54138204/

相关文章:

android - : attribute mutableText (aka yodgorbekkomilov. edgar.footballapp :mutableText) not found. ?

webassembly - 从不同语言编译的 WebAssembly 二进制文件的大小如何比较?

javascript - 监听 Web Worker 的创建?

javascript - 我如何从外部图表创建功能与 Amcharts 交互?

javascript - 在 JavaScript 中无法从 <div> 中找到 match()

rx-java - 递归地将Rx单例组合到Observable中

kotlin - 如何在 Jetpack Compose 中抛出 ScrollState?

c++ - C++ 类中的成功回调 Emscripten FETCH API

java - 从小程序调用javascript方法时出错

javascript - JQuery 轮播移动一个元素