我不知道如何将值异步传递给EM_ASM,下面是我尝试这样做的方法(但JS说它不是一个函数):
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
发布于 2020-09-08 19:19:58
我不知道如何传递回调,但是如果你想从JS返回一个值,那么docs有这样一个例子:你必须使用EM_ASM_INT
:
int x = EM_ASM_INT({
console.log('I received: ' + $0);
return $0 + 1;
}, 100);
printf("%d\n", x);
API reference有另一个返回字符串的示例:
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
。
https://stackoverflow.com/questions/63741179
复制相似问题