Artifact Content

Not logged in

Artifact 109289fec72a32d49dbb1bb9d8f50bf36b99177a


private import win32.windows;
private import std.string;

class WinDLLException : Exception
{
	private this( string msg ) { super(msg); }
}

class WinDLL
{
	// constructor:
	//   Load a DLL with specified name

	this( string dllname )
	{
		char original_cur[MAX_PATH];
		char sys[MAX_PATH];
		GetCurrentDirectoryA(MAX_PATH, original_cur.ptr);
		GetSystemDirectoryA(sys.ptr, MAX_PATH);
		SetCurrentDirectoryA(sys.ptr);
		handle = LoadLibraryA( dllname.ptr );
		SetCurrentDirectoryA(original_cur.ptr);
		if( handle is null )
			throw new WinDLLException( dllname ~ " not found" );
	}

	static WinDLL load( string name )
	{
		try {
			return new WinDLL(name);
		} catch(WinDLLException e) { return null; }
	}

	// close:
	//   free the DLL

	void close()
	{
		if( handle )
		{
			FreeLibrary( handle );
			handle = null;
		}
	}

	// get_api:
	//   extract a function with specified name from the DLL.
	//   may return null.

	template get_api(FnT)
	{
		FnT get_api( string apiname )
			in { assert(handle); }
			body
			{
				return cast(FnT) GetProcAddress( handle, apiname.toStringz() );
			}
	}

	// load_resource:
	//   extract a resource

	void* load_resource( string resname, char* type )
		in { assert(handle); }
		body
		{
			HRSRC hi = FindResource( handle, resname.toStringz(), type );
			if( hi is null )
				return null;
			HGLOBAL hr = LoadResource( handle, hi );
			if( hr is null )
				return null;
			return LockResource( hr );
		}

	// load_diaglog:
	//   specialized version of load_resource

	void* load_dialog( string resname )
	{
		return load_resource( resname, RT_DIALOG );
	}

	private HINSTANCE handle;
}