Last active
June 10, 2024 10:56
-
-
Save nokotan/504719a81e9def9bde791c8bc367b523 to your computer and use it in GitHub Desktop.
use externref in c code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// __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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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" | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Heh this looked promising but doesn't seem to compile with optimisations yet.