Get Dll functions at compile time

Johnson Jones via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 9 14:32:47 PDT 2017


Was buggy due to refactoring.


----------------------------


module DLLImport;

/* Import DLL functions in to type T. The following example shows 
methodology
struct DLL_gdk
{
	@("DLLImport") public static extern(Windows)
	{
		@("libgdk-3-0.dll")
		{
			void* function(GdkWindow *window) gdk_win32_window_get_handle;
		}
	}
}

// Fixes static functions and function pointers to point to their 
specified DLL's
ImportDLLs!DLL_gdk;
*/
void ImportDLLs(T)()
{
	version(Windows)
	{
		import core.sys.windows.windows, std.conv, std.meta, std.traits;
		HINSTANCE[string] DLLs;
	
		foreach(fname; __traits(allMembers, T))
		{	
			mixin("enum isf = isFunction!(T."~fname~");");
			mixin("enum isfp = isFunctionPointer!(T."~fname~");");
			mixin("enum attrs = __traits(getAttributes, T."~fname~");");		
			static if ((isf || isfp) && attrs.length == 2 && attrs[0] == 
"DLLImport")
			{
				auto dllName = attrs[1];
				if (dllName !in DLLs)
					DLLs[dllName] = LoadLibrary(to!wstring(dllName~"\0").ptr);

				auto dll = DLLs[dllName];
				if (dll == null)
					assert(0, "Cannot load DLL `"~dllName~"'");

				auto func = GetProcAddress(dll, fname);

				mixin("import "~moduleName!(T)~";");
				static if (isf)
					mixin("auto p = cast(void**)&"~T.stringof~"."~fname~"; *p = 
cast(typeof(p))func;");
				else static if (isfp)
					mixin(""~T.stringof~"."~fname~" = 
cast(typeof("~T.stringof~"."~fname~"))func;");	
				else
					static assert("DLLImport Error");
			}
		
		}
	}
}



More information about the Digitalmars-d-learn mailing list