tags:

views:

517

answers:

3

I've written two COM classes in C++, contained in a single MFC DLL. They're being loaded as plugins by a 3rd party application.

How can I get the file name, and version number, of the DLL from within those classes?

+5  A: 
TCHAR fileName[MAX_PATH + 1];
GetModuleFileName(hInstance, fileName, MAX_PATH);

Where hInstance is the one you get in the DllMain function. Don't use GetModuleHandle(0), because that returns the HINSTANCE of the host application.

StackedCrooked
I can't find any reference in the project to DllMain, I'm presuming that's because it's an MFC DLL as opposed to a Win32 one? Also, because the 3rd party app is instaciating the COM classes rather than calling LoadLibrary will DllMain (or equivalent) run and how do I pass the hInstance to the COM class, just store it in a global declared in stdafx.h?
Dave
AfxGetInstanceHandle should work.
StackedCrooked
+6  A: 

The main dll entry gives you the handle of your dll.

extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)

and

GetModuleFileName(hInstance, buffer, MAX_PATH);

can be used to get the filename of the dll.

GetFileVersionInfoSize
GetFileVersionInfo

will be used to get the file version.

Totonga
A: 
CString GetCallingFilename(bool includePath)
{
    CString filename;
    GetModuleFileName(AfxGetInstanceHandle(), filename.GetBuffer(MAX_PATH), MAX_PATH);

    filename.ReleaseBuffer();

    if( !includePath )
    {
     int filenameStart = filename.ReverseFind('\\') + 1;
     if( filenameStart > 0 )
     {
      filename = filename.Mid(filenameStart);
     }
    }

    return filename;
}

CString GetCallingVersionNumber(const CString& filename)
{
    DWORD fileHandle, fileVersionInfoSize;
    UINT bufferLength;
    LPTSTR lpData;
    VS_FIXEDFILEINFO *pFileInfo;

    fileVersionInfoSize = GetFileVersionInfoSize(filename, &fileHandle);
    if( !fileVersionInfoSize )
    {
     return "";
    }

    lpData = new TCHAR[fileVersionInfoSize];
    if( !lpData )
    {
     return "";
    }

    if( !GetFileVersionInfo(filename, fileHandle, fileVersionInfoSize, lpData) )
    {
     delete [] lpData;
     return "";
    }

    if( VerQueryValue(lpData, "\\", (LPVOID*)&pFileInfo, (PUINT)&bufferLength) ) 
    {
     WORD majorVersion = HIWORD(pFileInfo->dwFileVersionMS);
     WORD minorVersion = LOWORD(pFileInfo->dwFileVersionMS);
     WORD buildNumber = HIWORD(pFileInfo->dwFileVersionLS);
     WORD revisionNumber = LOWORD(pFileInfo->dwFileVersionLS);

     CString fileVersion;
     fileVersion.Format("%d.%d.%d.%d", majorVersion, minorVersion, buildNumber, revisionNumber);

     delete [] lpData;
     return fileVersion;
    }

    delete [] lpData;
    return "";
}
Dave