首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为c++的EM_ASM传递回调?

如何为c++的EM_ASM传递回调?
EN

Stack Overflow用户
提问于 2020-09-04 20:26:58
回答 1查看 244关注 0票数 0

我不知道如何将值异步传递给EM_ASM,下面是我尝试这样做的方法(但JS说它不是一个函数):

代码语言:javascript
运行
复制
const auto testFunc = [] (const char* data)
{
    printf("data: %s\n", data);
}
EM_ASM_(
{
    var funcResult = ($0);
    var text = "data";
    var lengthBytes = lengthBytesUTF8(text) + 1;
    var stringOnWasmHeap = _malloc(lengthBytes);
    stringToUTF8(text, stringOnWasmHeap, lengthBytes);
    // exception thrown: TypeError: funcResult is not a function
    funcResult(stringOnWasmHeap);
}, testFunc);

文档中说您可以使用em_str_callback_func类型的函数(em_str_callback_func)。但它没有说明如何使用它。https://emscripten.org/docs/api_reference/emscripten.h.html

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-08 19:19:58

我不知道如何传递回调,但是如果你想从JS返回一个值,那么docs有这样一个例子:你必须使用EM_ASM_INT

代码语言:javascript
运行
复制
int x = EM_ASM_INT({
  console.log('I received: ' + $0);
  return $0 + 1;
}, 100);
printf("%d\n", x);

API reference有另一个返回字符串的示例:

代码语言:javascript
运行
复制
char *str = (char*)EM_ASM_INT({
  var jsString = 'Hello with some exotic Unicode characters: Tässä on yksi lumiukko: ☃, ole hyvä.';
  var lengthBytes = lengthBytesUTF8(jsString)+1;
  // 'jsString.length' would return the length of the string as UTF-16
  // units, but Emscripten C strings operate as UTF-8.
  var stringOnWasmHeap = _malloc(lengthBytes);
  stringToUTF8(jsString, stringOnWasmHeap, lengthBytes);
  return stringOnWasmHeap;
});
printf("UTF8 string says: %s\n", str);
free(str); // Each call to _malloc() must be paired with free(), or heap memory will leak!

一旦你有了C中的值,你就可以直接调用你的testfunc

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63741179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档