Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Get Your DLL's Path/Name

30 Nov 2006 1  
Two methods to retrieve the path/name of a VS2002 or higher DLL from within that DLL.

Introduction

I'm working on a project that involves writing a plugin DLL for a game, and being the lazy programmer I am, I'm using the example provided by the game author and modifying it for my needs. I don't have access to the DLL's HINSTANCE (like we do with MFC DLLs). This presented a problem when I decided I needed to know the full path to the DLL in question.

The Code

Believe it or not, it only takes three lines of code to accomplish this task:
// near the top of your CPP file

EXTERN_C IMAGE_DOS_HEADER __ImageBase;

// and then, anywhere you need it:

LPTSTR  strDLLPath1 = new TCHAR[_MAX_PATH];
::GetModuleFileName((HINSTANCE)&__ImageBase, strDLLPath1, _MAX_PATH);

It seems that any EXE or DLL compiled with the VS2002 (and higher) linkers provides a psuedo-variable called __ImageBase that represents the DOS header of the module (all 32 bit binaries have this). Simply cast this variable to a HINSTANCE, and you can pass it as the first parameter to GetModuleFileName().

For those of you that need this functionality in VC6 or earlier, research the VirtualQuery() function. The approach is somewhat similar.

Disclaimers

I don't know if this will work in Vista.

The sample code includes source and the compiled EXE and DLL files.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here