关于webassembly:使用WebAssembly调用本地C程序自定义函数并返回页面

9次阅读

共计 923 个字符,预计需要花费 3 分钟才能阅读完成。

本 Demo 的目标

应用 WebAssembly 技术,通过浏览器调用 C 语言 自定义的函数,例子是实现 2 个变量相加,把计算出来的值返回 HTML 页面。

我的项目构造

├── index.html
└── main.c

C 语言

创立文件 main.c

int sum(int v1, int v2)
{return v1 + v2;}

HTML

创立文件 index.html

<html>
<head>
    <meta charset="utf-8" />
    <title>Demo</title>
</head>

<body>
    <div id="result"></div>
    <script type="text/javascript">
        var result;
        fetch("./main.wasm")
            .then(bytes => bytes.arrayBuffer())
            .then(mod => WebAssembly.compile(mod))
            .then(module => { return new WebAssembly.Instance(module) })
            .then(instance => {
                var v1=300;
                var v2=500;
                result = instance.exports.sum(300, 500);
                document.getElementById("result").innerHTML = "调用 C 函数 sum("+v1+","+v2+")后果如下:<br>"+v1+"+"+v2+"=" + result;
            });
    </script>
</body>
</html>

编译 wasm

main.c 源码文件编译成 main.wasm 文件

emcc  main.c -Os -s WASM=1 -s SIDE_MODULE=1 -o main.wasm

执行胜利后

├── index.html
├── main.c
└── main.wasm

运行一个 http 服务

将本地文件夹公布到 http 服务

 emrun --no_browser --port 8888 .

实现

浏览器关上 http://localhost:8888/ 即可查看后果。

调用 C 函数 sum(300,500)后果如下:300+500 = 800

留神

WebAssembly 是 2017 年推出的新技术,最好应用最新的浏览器,以反对 WebAssembly。

正文完
 0