Skip to content

Instantly share code, notes, and snippets.

@nokotan
Last active June 17, 2023 05:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nokotan/504719a81e9def9bde791c8bc367b523 to your computer and use it in GitHub Desktop.
Save nokotan/504719a81e9def9bde791c8bc367b523 to your computer and use it in GitHub Desktop.
use externref in c code
// __externref_t is a opaque pointer that will be translated to wasm externref.
__attribute__((import_name("receive_object")))
__externref_t receive_object(void);
__attribute__((import_name("send_object")))
void send_object(__externref_t);
int main() {
send_object(receive_object());
return 0;
}
// tested on emscripten 3.1.37
using fp_t = void (*__funcref)() ;
using main_t = int (*__funcref)();
int main() {
return 0;
}
// call funcref from c
// with emcc option -O0, invalid code will be generated.
// extern "C" is essential, as funcrefs cannot be mangled.
__attribute__((used))
extern "C" void importFuncRef(fp_t a) {
(*a)();
}
// this code causes compiler crash
// funcref pointer is in address space 20, but function pointers cannot be converted.
// __attribute__((used))
// extern "C" main_t exportMainAsFuncRef() {
// return (main_t)&main;
// }
// this asm code is required to call funcref
__asm(
".globl __funcref_call_table\n"
"__funcref_call_table:\n"
" .tabletype __funcref_call_table, funcref, 1\n"
);
@RReverser
Copy link

Heh this looked promising but doesn't seem to compile with optimisations yet.

@RReverser
Copy link

Nvm, got it to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment