如何将回调传递给 EM_ASM for c++?
How to pass a callback to EM_ASM for c++?
我不知道如何将值异步传递给EM_ASM,这是我尝试做的(但 JS 说它不是函数):
const auto testFunc = [] (const char* data)
{
printf("data: %s\n", data);
}
EM_ASM_(
{
var funcResult = ([=11=]);
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
我不知道传递回调,但是如果你想做的是 return 来自 JS 的值,那么 docs 有这样的例子:你必须使用 EM_ASM_INT
改为:
int x = EM_ASM_INT({
console.log('I received: ' + [=10=]);
return [=10=] + 1;
}, 100);
printf("%d\n", x);
API reference 还有另一个 returning 字符串的例子:
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
。
我不知道如何将值异步传递给EM_ASM,这是我尝试做的(但 JS 说它不是函数):
const auto testFunc = [] (const char* data)
{
printf("data: %s\n", data);
}
EM_ASM_(
{
var funcResult = ([=11=]);
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
我不知道传递回调,但是如果你想做的是 return 来自 JS 的值,那么 docs 有这样的例子:你必须使用 EM_ASM_INT
改为:
int x = EM_ASM_INT({
console.log('I received: ' + [=10=]);
return [=10=] + 1;
}, 100);
printf("%d\n", x);
API reference 还有另一个 returning 字符串的例子:
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
。