Skip to content

Instantly share code, notes, and snippets.

@adamziel
Created October 10, 2023 11:10
Show Gist options
  • Save adamziel/9c7d3302407294e12d9c1d1eaa54cdba to your computer and use it in GitHub Desktop.
Save adamziel/9c7d3302407294e12d9c1d1eaa54cdba to your computer and use it in GitHub Desktop.
Working dlopen example in Emscripten
#!/bin/bash
emcc ./module.c -sSIDE_MODULE -o module.o
emcc ./main.c \
-lnodefs.js \
-o ./main.js \
-sMAIN_MODULE \
-sEXPORTED_FUNCTIONS='["_main","ccall", "UTF8ToString", "lengthBytesUTF8", "FS"]' \
-sEXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "UTF8ToString", "lengthBytesUTF8", "FS"]' \
-sFORCE_FILESYSTEM=1
node ./main.js
#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>
typedef void (*hello_func)();
int main() {
void* handle = dlopen("./module.o", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
return 1;
}
hello_func func = (hello_func) dlsym(handle, "helloworld");
if (!func) {
fprintf(stderr, "%s\n", dlerror());
dlclose(handle);
return 1;
}
func();
dlclose(handle);
return 0;
}
#include <stdio.h>
void helloworld() {
printf("Hello, world!\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment