我正在尝试制作一个简单的网站,显示来自 javascript 文件的函数调用结果,该函数调用 WASM 文件。到目前为止我有以下文件:
生成文件
FILES = add.c
OUTPUT = MyWasmLib
CC = emcc
EMCC_VERSION := $(shell command -v $(CC) 2> /dev/null)
EMCC_FLAGS = -s EXPORT_ALL=1 -s EXPORTED_RUNTIME_METHODS='["cwrap"]' -s ALLOW_MEMORY_GROWTH=1 -s EXPORT_ES6=1 -sMODULARIZE
all: check_emcc $(OUTPUT)
check_emcc:
ifndef EMCC_VERSION
$(error "emcc is not installed. please install emscripten.")
endif
$(OUTPUT): $(FILES)
$(CC) $(EMCC_FLAGS) -o [email protected] $(filter %.c, $(FILES))
clean:
rm -i $(OUTPUT).js $(OUTPUT).wasm
.PHONY: all check_emcc clean
添加.c
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
return a + b;
}
wasm_mjs_interface.js
import { default as MyWasmLib } from "./MyWasmLib.js";
let addWasmFunction;
let WASM_initialized;
const initializeWASM = () => {
WASM_initialized = new Promise((resolve, reject) => {
MyWasmLib.onRuntimeInitialized = () => {
try {
addWasmFunction = MyWasmLib.cwrap(
"add", "number", ["number", "number"]
);
resolve();
}
catch (error) {
reject(error);
}
};
});
};
initializeWASM();
export const WASM_add = async (a, b) => {
await WASM_initialized;
try {
return addWasmFunction(a, b);
}
catch (error) {
console.error("Error calling add function in WASM: ", error);
throw error;
}
};
index.js
import { WASM_add } from "./wasm_mjs_interface.mjs";
async function loadWasmAdd() {
try {
const result = await WASM_add(5, 3);
console.log("WASM addition result: ", result);
document.getElementById("result").textContent = `${result}`;
}
catch (error) {
console.error("Error performing WASM addition: ", error);
}
}
if (document.readyState === "loading") {
window.addEventListener("DOMContentLoaded", loadWasmAdd);
} else {
loadWasmAdd();
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>WASM Module Example</title>
<script type="module" src="./index.js"></script>
</head>
<body>
<p id="result"></p>
</body>
</html>
我正在运行一个简单的Python服务器
python3 -m http.server 8000
我正在使用
查看服务器firefox 0.0.0.0:8000/index.html
最后我遇到的问题是,在实际的控制台和页面上没有任何反应。在控制台中,我可以看到有一个对index.html MyWasmLib.js 和 wasm_mjs_interface.mjs 的 GET 请求,但是控制台中没有错误,并且在我有 p 标签的浏览器中实际上没有显示任何内容。
我不确定你如何用 emscripten 解决这个问题,但是tiny-wasm-runtime(我写的)有一些例子可以完成你想要做的事情,包括 python 服务器。