tyme4ts icon indicating copy to clipboard operation
tyme4ts copied to clipboard

统一跨语言支持

Open whinc opened this issue 1 year ago • 2 comments

一直使用 lunar,现在有看到 6tail 积极迭代新版的 typme4ts,很是感动,尤其是维护多语言版本是个非常消耗时间的工作,为了让 6tali 的精力聚焦到核心的算法上,提议使用 rust/c++ 编写核心算法,编译成 wasm 后提供,目前主流语言都支持直接加载 wasm 使用(或者提供薄薄的一层语言绑定),这样可以减少多语言维护压力,保持核心算法一致性,提升性能。

Rust/C++ -> wasm -> js/ts/java/go/python/c#

以下是使用 JavaScript、Java、Go 和 Python 调用 WebAssembly (WASM) 模块的代码示例。假设我们有一个简单的 WASM 模块 example.wasm,它导出一个函数 add,用于将两个数字相加。

JavaScript(浏览器)

<!DOCTYPE html>
   <head>
      <meta charset="utf-8">
      <title>WebAssembly Add example</title>
      <style>
         div {
            font-size : 30px; text-align : center; color:blue;
         }
      </style>
   </head>
   <body>
      <div id="textcontent"></div>
      <script>
         let sum;
         fetch("add.wasm")
            .then((response) => response.arrayBuffer())
            .then((bytes) => WebAssembly.instantiate(bytes))
            .then((results) => {
                sum = results.instance.exports.add(13, 12);
                console.log("The result of 13 + 12 = " +sum);
                document.getElementById("textcontent").innerHTML = "The result of 13 + 12 = " +sum;
         });
      </script>
   </body>
</html>

JavaScript(node.js)

const fs = require('fs');
const wasmBuffer = fs.readFileSync('example.wasm');

WebAssembly.instantiate(wasmBuffer).then(result => {
  const add = result.instance.exports.add;
  console.log(add(2, 3)); // 输出: 5

});

Java

Java 可以使用 wasmtime-java 库来调用 WASM。

首先,添加依赖:

<dependency>
  <groupId>org.wasmtime</groupId>
  <artifactId>wasmtime</artifactId>
  <version>0.30.0</version>
</dependency>

然后,编写代码:

import org.wasmtime.*;

public class WasmExample {
    public static void main(String[] args) throws Exception {
        Engine engine = new Engine();
        Module module = Module.fromFile(engine, "example.wasm");
        Store<Void> store = new Store<>(engine);
        Instance instance = new Instance(store, module, new Linker(store).link());
        Func add = instance.getFunc(store, "add").orElseThrow();
        int result = add.invoke(store, 2, 3).orElseThrow();
        System.out.println(result); // 输出: 5
    }
}

Go

Go 可以使用 wasmer-go 库来调用 WASM。

首先,安装库:

go get github.com/wasmerio/wasmer-go/wasmer

然后,编写代码:

package main

import (
	"fmt"
	"github.com/wasmerio/wasmer-go/wasmer"
)

func main() {
	wasmBytes, _ := wasmer.ReadBytes("example.wasm")
	store := wasmer.NewStore(wasmer.NewEngine())
	module, _ := wasmer.NewModule(store, wasmBytes)
	importObject := wasmer.NewImportObject()
	instance, _ := wasmer.NewInstance(module, importObject)

	add := instance.Exports.GetFunction("add")
	result, _ := add(2, 3)
	fmt.Println(result) // 输出: 5
}

Python

Python 可以使用 wasmer-python 库来调用 WASM。

首先,安装库:

pip install wasmer

然后,编写代码:

from wasmer import engine, store, module, instance

# 加载 WASM 文件
with open('example.wasm', 'rb') as f:
    wasm_bytes = f.read()

# 创建引擎和存储
engine = engine.JIT()
store = store.Store(engine)

# 编译模块
module = module.Module(store, wasm_bytes)

# 实例化模块
instance = instance.Instance(module)

# 调用导出的函数
add = instance.exports.add
result = add(2, 3)
print(result)  # 输出: 5

这些示例展示了如何在不同语言中调用 WASM 模块。请确保你已经安装了相应的库,并且 WASM 模块 example.wasm 存在于你的工作目录中。

whinc avatar Oct 20 '24 04:10 whinc

非常感谢,tyme已经有tyme4j,tyme4net,tyme4rust,tyme4go,tyme4php,tyme4swift也在路上了,wasm很美好,但我感觉驾驭不住,因为说实话我自己都很讨厌rust的很多设计理念,更不敢保证转出来的东西能变得易用。当然,我也会去尝试wasm方面的研究。

6tail avatar Oct 20 '24 05:10 6tail

非常感谢,tyme已经有tyme4j,tyme4net,tyme4rust,tyme4go,tyme4php,tyme4swift也在路上了,wasm很美好,但我感觉驾驭不住,因为说实话我自己都很讨厌rust的很多设计理念,更不敢保证转出来的东西能变得易用。当然,我也会去尝试wasm方面的研究。

👍 能编译成 wasm 的不止 rust,还有其他不少语言,不过可以等熟悉后考虑,期待后面第三代等见到~

whinc avatar Oct 20 '24 07:10 whinc