使用“mergeInto(LibraryManager.library……”注入的方法不能直接使用闭包。
目录
一、创建show_answer.cc
#ifndef EM_PORT_API
#if defined(__EMSCRIPTEN__)
#include <emscripten.h>
#if defined(__cplusplus)
#define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE
#else
#define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE
#endif
#else
#if defined(__cplusplus)
#define EM_PORT_API(rettype) extern "C" rettype
#else
#define EM_PORT_API(rettype) rettype
#endif
#endif
#endif
#include <stdio.h>
EM_PORT_API(int) show_me_the_answer();
EM_PORT_API(void) func() {
printf("%d\n", show_me_the_answer());
}
二、创建pkg.js库文件
mergeInto(LibraryManager.library, {
show_me_the_answer: function () {
return jsShowMeTheAnswer();
}
})
三、编译wasm
emcc code/1207/show_answer.cc --js-library code/1207/pkg.js -o code/1207/show_answer.js
编译后文件为:

四、创建html文件实现方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function f1(){
var answer = 42;
function f2() {
return answer;
}
return f2;
}
var jsShowMeTheAnswer = f1();
Module = {};
Module.onRuntimeInitialized = function() {
Module._func();
}
</script>
<script src="show_answer.js"></script>
</body>
</html>
在浏览器中运行html后F12输出如下结果:

使用这种方法,不仅可以绕过“mergeInto(LibraryManager.library……”注入的方法不仅能直接使用闭包的限制,还可以动态调整注入函数的行为
本文介绍了一种通过创建C/C++与JavaScript桥接的方法,实现了WebAssembly模块与JavaScript之间的灵活交互,尤其针对如何绕过特定限制并利用闭包进行了详细讲解。
1664





