亚当的动态库

//接口用来分类
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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值