Go lang 실습

golang wasm - 2

컴닥 2024. 3. 6. 17:29
반응형

자바스크립트에서 고의 함수를 호출하는 예...

다른 언어를 넘나들기 위해서는 자료형 부분이 가장 먼저 신경 쓰이는데.. 

package main

import (
	"fmt"
	"syscall/js"
)

func main() {
	js.Global().Set("greet", js.FuncOf(
        func(this js.Value, args []js.Value) interface{} {
		    if len(args) == 0 {
			    return "Hello, World!"
		    }
		return fmt.Sprintf("Hello, %s!", args[0].String())
	}))

	select {}
}

js.Value라는 자료형을 이용해서 args를 받고..
함수의 결과는 빈 인터페이스를 이용해서 보내는 군...

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Go WebAssembly Example</title>
</head>
<body>
    <script src="wasm_exec.js"></script>
    <script>
        async function runWasm() {
            const go = new Go();
            const result = await WebAssembly.instantiateStreaming(
                fetch("main.wasm"), go.importObject
            );
            go.run(result.instance);

            console.log(window.greet());
            console.log(window.greet("John"));
        }

        runWasm();
    </script>
</body>
</html>

문자열을 주고 받는 건 알겠는데...
배열이나 맵을 저비용으로 빠르게 주고 받는 방법은 없으려나...
일단 JSON으로 주고 받으면 되지만...

반응형