Emscripten提供了多种在C环境调用JavaScript的方法,包括:
EM_JS
/EM_ASM
宏内联JavaScript代码、emscripten_run_script
函数、JavaScript函数注入(更准确的描述为:“Implement C API in JavaScript”,既在JavaScript中实现C函数API
)。本次是使用第三种JS注入。
目录
一、创建C函数
//capi_js.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)
js_add(int a, int b);
EM_PORT_API(void)
js_console_log_int(int param);
EM_PORT_API(void)
print_the_answer()
{
int i = js_add(21, 21);
js_console_log_int(i);
}
EM_PORT_API 的解释参考之前的文章: 在JavaScript中调用C/C++导出的方法_YouziSama66的博客-CSDN博客
print_the_answer()
调用了函数js_add
计算21+21,然后调用js_console_log_int()
来打印结果,后二者仅仅给出了声明,函数实现将在JavaScript中完成。
二、创建JavaScript实现C方法
//pkg.js
mergeInto(LibraryManager.library, {
js_add: function (a, b) {
console.log("js_add");
return a + b;
},
js_console_log_int: function (param) {
console.log("js_console_log_int:" + param);
}
})
LibraryManager.library
可以简单的理解为JavaScript注入C环境的库。
三、编译wasm文件
代码如下:
emcc code/capi_js.cc --js-library code/pkg.js -o code/capi_js.js
--js-library pkg.js意为将pkg.js作为附加库参与链接。命令执行后得到capi_js.js以及capi_js.wasm。
编译后得到对应文档:
四、创建html文档实现方法
创建对应html文档并C调用导出的方法:
<!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>capi_js</title>
</head>
<body>
<script>
Module = {};
Module.onRuntimeInitialized = function () {
Module._print_the_answer();
}
</script>
<script src="capi_js.js"></script>
</body>
</html>
浏览器控制台输出对应结果
下一篇文章处理闭包的问题。