【wasm】hello world

本文介绍了如何在Windows环境下搭建WebAssembly开发环境,通过Emscripten编译C代码生成WebAssembly,并演示了如何从JavaScript调用WebAssembly中的C函数。步骤包括安装依赖、创建 HelloWorld 示例、以及导出和调用C函数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、windows环境搭建

先安装cmake、git,然后:

git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
git pull
emsdk install latest
emsdk activate latest
emsdk_env.bat
#emsdk update #升级命令,备用

二、最简helloworld

mkdir hello
cd hello

创建hello.c:

#include <stdio.h>
int main(int argc, char ** argv) {
	printf("Hello, world!\n");
}

编译运行:
emcc hello.c -s WASM=1 -o hello.html
emrun --no_browser --port 8080 .

用浏览器打开:http://localhost:8080/hello.html

三、使用JavaScrip调用WebAssembly函数

hello.c:

#include <stdio.h>
#include <emscripten/emscripten.h>

int main(int argc, char ** argv) {
    printf("Hello World\n");
}

#ifdef __cplusplus
extern "C" {
#endif

int EMSCRIPTEN_KEEPALIVE myFunction(int argc, char ** argv) {
  printf("我的函数已被调用\n");
}

#ifdef __cplusplus
}
#endif

编译: 

emcc hello.c -s WASM=1 -o hello.html -s "EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']"

编译参数: -s "EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']" 表示导出ccall和cwrap两个函数

运行后在console中手动调用 Module.ccall('myFunction', null, null, null)

Module.ccall中的4个参数分别指:C函数名,返回类型,参数类型(数组)和参数(也是数组)。

例如,如果函数接受2个字符串作为参数,我们需要通过这样调用它:

Module.ccall('hello','number',['string','string'],['hello','world'])

可以使用的类型有null,string,number,array和boolean。

我们还可以使用Module.cwrap函数为hello函数创建一个JavaScript打包,这样我们可以使用JS函数多次调用该函数:

const hello = Module.cwrap('myFunction', 'number', null, null)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值