Hi! How can I call exported kotlin function from `...
# webassembly
i
Hi! How can I call exported kotlin function from
@JsFun
? For instance, consider this code:
Copy code
@JsFun(
    """
        (value) => kotlinSquare(value)
    """
)
external fun square(value: Int): Int

@JsExport
fun kotlinSquare(value: Int): Int {
    return value * value
}
What is the correct way to call
kotlinSquare
? I’m running
wasmJs
on nodejs runtime.
a
In a Kotlin-way, there is no option. What kind of problems are you trying to solve?
i
I’m currently trying to write a JS wrapper over Kotlin Array to make a benchmark (see https://youtrack.jetbrains.com/issue/KT-57125/Add-interop-with-JavaScript-arrays-to-Kotlin-Wasm#focus=Comments-27-9720157.0-0). I was hoping to be able to make something like this:
Copy code
@JsFun(
    """
        (array) => ({
            length: kotlinArrayLength(array),
            [Symbol.iterator]: function* () {
              let i = 0;
              while (i < kotlinArrayLength(array)) {
                yield kotlinArrayGet(i);
                i++;
              }
            },
            get: (index) => kotlinArrayGet(array, index),
            set: (index, value) => kotlinArraySet(array, index, value)
        })
    """
)
external fun wrapKotlinArrayWithJsMethods(array: JsReference<IntArray>): JsArray<JsNumber>

@JsExport
fun kotlinArrayLength(ref: JsReference<IntArray>): Int {
    return ref.get().size
}

@JsExport
fun kotlinArrayGet(ref: JsReference<IntArray>, index: Int): Int {
    return ref.get()[index]
}

@JsExport
fun kotlinArraySet(ref: JsReference<IntArray>, index: Int, value: Int) {
    ref.get()[index] = value
}
But as you can see, I need to call kotlin exported functions to make this work.
a
Oh, I see. You could try a dark magic spell - `wasmExports`:
Copy code
@JsFun(
    """
        (array) => ({
            length: kotlinArrayLength(array),
            [Symbol.iterator]: function* () {
              let i = 0;
              while (i < kotlinArrayLength(array)) {
                yield wasmExports["kotlinArrayGet"](i);
                i++;
              }
            },
            get: (index) => kotlinArrayGet(array, index),
            set: (index, value) => kotlinArraySet(array, index, value)
        })
    """
)
external fun wrapKotlinArrayWithJsMethods(array: JsReference<IntArray>): JsArray<JsNumber>
But it's not what we are committing to support (because it's based on internal implementation knowledge). In your case, I think it could help because it's not a code that is supposed to live in more than 1 Kotlin version, right? 😅
i
Sure, thanks!
a
Does it work?
i
Yes, thanks) Now I have to fix other errors 🙂
🫡 1