//接口用来分类
interface A {
//内部,实际定义不变
extern(C) /* etc*/ {
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;
//包含A接口的C库,dll,动态加载,当然得找得到你的库
void main() {
import core.stdc.stdio;
libc.load();
//旧代码依然工作
printf("你好%d\n", 45);
}
亚当的动态库
原创
©著作权归作者所有:来自51CTO博客作者fqbqrr的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:c++安全编写对象池中文版
下一篇:csdn又出什么问题啦.
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
亚当2014年的演讲
亚当2014年的演讲。
编译器 数组 数据 内联汇编 演讲 -
iOS 静态库动态库的选择 静态库和动态库
库:从本质来说是一种可执行的二进制代码,与具体的硬件平台有关系。 静态库与动态库(它们从被载入内在的时间不同) 静态库:它是在编译时(具体是在连接时)把库中的相关代码复制到程序中去。 优点:程序运行时不需要库 缺点:程序的体积偏大, &nb
iOS 静态库动态库的选择 静态库 动态库 静态库与动态库的区别 加载