Skip to content

Instantly share code, notes, and snippets.

@DavidYKay
Created October 23, 2018 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidYKay/7e0c399211064d4809ed3649e71aa9ff to your computer and use it in GitHub Desktop.
Save DavidYKay/7e0c399211064d4809ed3649e71aa9ff to your computer and use it in GitHub Desktop.
Simple example of loading/unloading DLLs in D. This could be extended to provide a hot-swapping mechanism.
import core.stdc.stdio;
extern (C) int dll() {
printf("hello from dll A!\n");
return 0;
}
shared static this() {
printf("liba.so shared static this\n");
}
shared static ~this() {
printf("liba.so shared static ~this\n");
}
import core.stdc.stdio;
extern (C) int dll() {
printf("hello from dll B!\n");
return 0;
}
shared static this() {
printf("libb.so shared static this\n");
}
shared static ~this() {
printf("libb.so shared static ~this\n");
}
import core.stdc.stdio;
import core.stdc.stdlib;
import core.sys.posix.dlfcn;
import std.string;
extern (C) int dll();
void* loadAndRunDll(string dllPath) {
void* lh = dlopen(toStringz(dllPath), RTLD_LAZY);
if (!lh) {
fprintf(stderr, "dlopen error: %s\n", dlerror());
exit(1);
}
printf("libmyfn.so is loaded\n");
int function() fn = cast(int function())dlsym(lh, "dll");
char* error = dlerror();
if (error) {
fprintf(stderr, "dlsym error: %s\n", error);
exit(1);
}
printf("dll() function is found\n");
fn();
return lh;
}
int main() {
printf("+main()\n");
void* ah = loadAndRunDll("liba.so");
printf("unloading DLL A\n");
dlclose(ah);
printf("getting user input...\n");
void* bh = loadAndRunDll("libb.so");
printf("unloading DLL B\n");
dlclose(bh);
printf("-main()\n");
return 0;
}
shared static this() { printf("main shared static this\n"); }
shared static ~this() { printf("main shared static ~this\n"); }
project('hotproj', 'd',)
libA = shared_library('a', 'dll.d')
libB = shared_library('b', 'dll2.d')
executable('hotswap', 'hotswap.d',
link_with : [libA, libB])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment