在Mac上把 C 程序编译为 wasm 在浏览器上运行

文章详细介绍了如何下载和安装emsdk,然后使用它将C程序编译为WebAssembly模块,并将该模块嵌入到HTML中,通过JavaScript调用C函数,展示了WebAssembly与浏览器环境的交互过程。

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

下载 emsdk

git clone https://github.com/juj/emsdk.git
cd emsdk
 
./emsdk install latest
./emsdk activate latest

新建 hello.c 程序

#include <emscripten/emscripten.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
int main(){
	return 0;
}


#ifdef __cplusplus
#define EXTERN extern "C"
#else
#define EXTERN
#endif

EXTERN EMSCRIPTEN_KEEPALIVE int hello(char *buf) {
  printf("hello:%s\n", buf);
  buf[0] = 'X';
  buf[1] = 'X';
  buf[2] = 'X';
  printf("hello:%s\n", buf);
  return 0;
}

新建 temp.html

<button id="mybutton">click</button>
{{{ SCRIPT }}}
<script>
document.getElementById("mybutton").addEventListener("click", () => {
var myTypedArray = new Int32Array([65, 66, 67, 68, 69,0]);

var buf = Module._malloc(myTypedArray.length*myTypedArray.BYTES_PER_ELEMENT);
Module.HEAPU8.set(myTypedArray, buf);
  
Module.ccall('hello', 'number', ['number'], [buf]);

console.log( Module.HEAPU8[buf]);
console.log( Module.HEAPU8[buf+1]);
console.log( Module.HEAPU8[buf+2]);
console.log( Module.HEAPU8[buf+3]);

Module._free(buf);
});
</script>

编译

emcc -o hello.html hello.c --shell-file temp.html -s NO_EXIT_RUNTIME=1  -s EXPORTED_RUNTIME_METHODS="['ccall']" -s EXPORTED_FUNCTIONS="['_main','_hello', '_malloc','_free']"

把生成文件放到 nginx 上就OK了

hello.wasm
hello.js
hello.html
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值