Embind方便的实现js与C++的交互

本文介绍了如何使用Embind库方便地实现JavaScript与C++之间的交互。通过示例展示了如何导出C++的函数到JavaScript,包括基本类型、字符串操作以及类的方法。同时,也提到了使用`EM_JS`宏来编写JavaScript代码并在C++中调用。文章最后展示了完整的C++代码示例,涵盖了从基本类型到类的实例方法的交互过程。
摘要由CSDN通过智能技术生成

#include <emscripten.h>
#include <emscripten/bind.h>//EMSCRIPTEN_BINDINGS 的头文件
#include <iostream>
#include <string>
#include <math.h>
#include <stdio.h>
//#include <SDL.h>
using namespace emscripten;//EMSCRIPTEN_BINDINGS 中的 function
using namespace std;
// 注意extern “C” 中的C要大写
extern "C" int EMSCRIPTEN_KEEPALIVE myFunction(int argc, char **argv)
{
    cout<<"这是一个测试函数"<<endl;
    return 0;
}

 extern "C" char* EMSCRIPTEN_KEEPALIVE outName(char *n)
 {
    char xhName[] = "xuanhun";
    strcat(n, xhName);
    cout<<"outName = "<<n<<endl;
    return n;
 }

// 在浏览器控制台 可以执行 Module._myFunction() 函数,注意是extern "C"
// 函数名只会在前面加一个下划线,否则名称就比较繁琐
// main函数也是默认导出的函数 可以使用 Module._main() 来执行

EM_JS(void, call_alert, (), {
  alert('hello world!');
  console.log("EM_JS,nihao!");
  //throw 'all done';
});

EM_JS(int, call_add, (int a,int b), {
    console.log("EM_JS,add!");
  return a + b;
});

//Null-terminated C strings can also be passed into EM_JS functions, 
//but to operate on them, they need to be copied out from the heap to convert to high-level JavaScript strings.
// use connsole.log('hello ' + UTF8ToString(str));
EM_JS(char*, call_add_string, (char* a,char* b), {
    console.log("EM_JS,add_string!");
    console.log(UTF8ToString(a));
    var s = "hello,jsStr";
    //return a;//也可以
    
    var returnStr = "Hello C#!";
    var bufferS

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程经验随笔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值