Check to see if your .dll or .exe is a .NET assembly in unmanaged C++

posted @ Monday, November 15, 2004 8:03 PM

 

Javier recently made an interesting post on how to check to see if a .dll or .exe is in fact a .NET assembly or not. This can also be done in unmanaged code so I took this as an opportunity to sit down and write a quick example of how we can check a file to see if it is a .NET Assembly. This is what I came up with.

#include "cor.h"
#include <stdio.h>
bool IsAssembly(char file[]);
int main(int argc, char* argv[])
{
bool bIsAssembly = false;
bIsAssembly = IsAssembly(argv[1]);
if(bIsAssembly)
printf("I am a .NET Assembly.\n");
else
printf("I am not .NET Assembly.\n");
return 0;
}
bool IsAssembly(char file[])
{
bool bIsAssembly = false;
HRESULT hr;
mdAssembly asmToken;
IMetaDataDispenser* pIMetaDataDispenser;
IMetaDataAssemblyImport* pIMetaDataAssemblyImport;
CoInitialize(0);
hr = CoCreateInstance(CLSID_CorMetaDataDispenser, 0,
CLSCTX_INPROC_SERVER, IID_IMetaDataDispenser,
(LPVOID*)&pIMetaDataDispenser);
wchar_t filename[MAX_PATH];
mbstowcs(filename, file, lstrlen(file)+1);
if(SUCCEEDED(hr))
{
hr = pIMetaDataDispenser->OpenScope(filename, ofRead,
IID_IMetaDataAssemblyImport,
(LPUNKNOWN*)&pIMetaDataAssemblyImport);
if(SUCCEEDED(hr))
{
hr = pIMetaDataAssemblyImport->GetAssemblyFromScope(&asmToken);
if(hr == S_OK)
bIsAssembly = true;
else
bIsAssembly = false;
pIMetaDataAssemblyImport->Release();
}
pIMetaDataDispenser->Release();
}
CoUninitialize();
return bIsAssembly;
}