JavaScript函数方法注入C/C++

Emscripten提供了多种在C环境调用JavaScript的方法,包括:EM_JS/EM_ASM宏内联JavaScript代码、emscripten_run_script函数、JavaScript函数注入(更准确的描述为:“Implement C API in JavaScript”,既在JavaScript中实现C函数API)。

本次是使用第三种JS注入。

目录

一、创建C函数

二、创建JavaScript实现C方法

三、编译wasm文件

四、创建html文档实现方法


一、创建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>

 浏览器控制台输出对应结果

下一篇文章处理闭包的问题。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值