Artifact Content

Not logged in

Artifact 66565a0003521f7b828caa8975bf769301203af6


private import win32.ansi.windows;

class WinDLLException : Exception
{
	private this( char[] msg ) { super(msg); }
}

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

	this( char[] dllname )
	{
		char original_cur[MAX_PATH];
		char sys[MAX_PATH];
		GetCurrentDirectory(MAX_PATH, original_cur);
		GetSystemDirectory(sys, MAX_PATH);
		SetCurrentDirectory(sys);
		handle = LoadLibrary( dllname );
		SetCurrentDirectory(original_cur);
		if( handle is null )
			throw new WinDLLException( dllname ~ " not found" );
	}

	static WinDLL load( char[] 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( char[] apiname )
			in { assert(handle); }
			body
			{
				return cast(FnT) GetProcAddress( handle, apiname );
			}
	}

	// load_resource:
	//   extract a resource

	void* load_resource( char[] resname, char* type )
		in { assert(handle); }
		body
		{
			HRSRC hi = FindResource( handle, resname, 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( char[] resname )
	{
		return load_resource( resname, RT_DIALOG );
	}

	private HINSTANCE handle;
}