WebAssembly - 用 C 語言編寫



在本章中,我們將把一個簡單的 C 程式編譯成 JavaScript,並在瀏覽器中執行該程式。

例如 - C 程式

#include<stdio.h> 
int square(int n) { 
   return n*n; 
}

我們在 wa/ 資料夾中安裝了 emsdk。在同一資料夾中,再建立一個 cprog/ 資料夾,並將上面的程式碼儲存為 square.c。

我們在前一章中已安裝了 emsdk。在此,我們將使用 emsdk 編譯上述 c 程式碼。

在命令提示符中編譯 test.c,如下所示 -

emcc square.c -s STANDALONE_WASM –o findsquare.wasm

emcc 命令負責編譯程式碼以及給你提供 .wasm 程式碼。我們使用 STANDALONE_WASM 選項,該選項只會提供 .wasm 檔案。

示例 - findsquare.html

<!doctype html> 
<html>
   <head>
      <meta charset="utf-8">
      <title>WebAssembly Square function</title>
      <style>
         div { 
            font-size : 30px; text-align : center; color:orange; 
         } 
      </style>
   </head> 
   <body>
      <div id="textcontent"></div>
      <script> 
      let square; fetch("findsquare.wasm").then(bytes => bytes.arrayBuffer()) 
      .then(mod => WebAssembly.compile(mod)) .then(module => {
         return new WebAssembly.Instance(module) 
      }) 
      .then(instance => {
         square = instance.exports.square(13); 
         console.log("The square of 13 = " +square);         
         document.getElementById("textcontent").innerHTML = "The square of 13 = " +square; 
      }); 
      </script>
   </body>
</html>

輸出

輸出如下所示 -

Find Square HTML
廣告