[WASM] Create and Run a Native WebAssembly Function
In this introduction, we show a simple WebAssembly function that returns the square root of a number. To create this function we load up WebAssembly Explorer (https://mbebenita.github.io/WasmExplorer/), writing the native WAST code to create and export the function. We compile and download the resulting WebAssembly binary, loading this with the Fetch API and WebAssembly JavaScript API to call the function in the browser.
Demo Repo: https://github.com/guybedford/wasm-intro
(module
)
Define a function inside the module:
(module
(func $sqrt
)
)
Now we defined a empty function,
To add input and output we can do:
(module
(func $sqrt
(param $num f32) # Input: param is the keyword, $num is the param name, f32 is the type
(result f32) # Output: result is the keyword, f32 is the type
)
)
Now we can define function body:
(module (func $sqrt (param $num f32) (result f32) (f32.sqrt (get_local $num)) # call the function sqrt on f32, pass in the params $num though get_local function ) )
The calculation value will be the return value.
If we want to use the fucntion in Javascript, we need to export the function:
(module (export "sqrt" (func $sqrt)) # export the function call "sqrt" refer to $sqrt function we defined below (func $sqrt (param $num f32) (result f32) (f32.sqrt (get_local $num)) ) )
After "Assemble" it and "Download" the file, we can load in the project:
<!doctype> <html> <header> <title> WASM </title> <script> fetch('./test.wasm') .then((res) => { if(res.ok){ return res.arrayBuffer(); } throw new Error('Unable to fetch WASM') }) .then((bytes)=> { return WebAssembly.compile(bytes); }) .then(module => { return WebAssembly.instantiate(module); }) .then(instance => { window.wasmSqrt =instance.exports.sqrt; }) </script> </header> </html>
Open the console, we can type:
wasmSqrt(25) //5
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2016-06-27 [Javascript] bukld 'SQL' like object tree
2016-06-27 [Javascript] Implement zip function
2016-06-27 [Javascript] Immute Object