interface A {
extern(C) {
int printf(const char*, ...);
int atoi(const char*);
}
}
private mixin template DynamicLoad(Iface, string library) {
static foreach(name; __traits(derivedMembers, Iface))
mixin("typeof(&__traits(getMember, Iface, name)) " ~ name ~ ";");
private void* libHandle;
void load() {
version(Posix) {
import core.sys.posix.dlfcn;
libHandle = dlopen("lib" ~ library ~ ".so", RTLD_NOW);
} else version(Windows) {
import core.sys.windows.windows;
libHandle = LoadLibrary(library ~ ".dll");
alias dlsym = GetProcAddress;
}
if(libHandle is null)
throw new Exception("加载"~library~"失败");
foreach(name; __traits(derivedMembers, Iface)) {
alias tmp = mixin(name);
tmp = cast(typeof(tmp))dlsym(libHandle, name);
if(tmp is null) throw new Exception("从" ~library~"加载" ~ name ~"失败");
}
}
void unload() {
version(Posix) {
import core.sys.posix.dlfcn;
dlclose(libHandle);
} else version(Windows) {
import core.sys.windows.windows;
FreeLibrary(libHandle);
}
foreach(name; __traits(derivedMembers, Iface))
mixin(name ~ " = null;");
}
}
mixin DynamicLoad!(A, "c") libc;
void main() {
import core.stdc.stdio;
libc.load();
printf("你好%d\n", 45);
}