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