I'm working with native CLR hosting for some weeks now. In the beginning it worked pretty well. But later on I've noticed that something in my application causes heap corruption. I've figured out that this is caused by the CLR startup. (See following short version of the code.)
#pragma comment(lib, "mscoree.lib")
#include <mscoree.h>
#include <metahost.h>
#include <comdef.h>
#import "mscorlib.tlb" raw_interfaces_only \
high_property_prefixes("_get","_put","_putref") \
rename("ReportEvent", "InteropServices_ReportEvent")
using namespace mscorlib;
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr; // In fullversion used for error detection - but here unused.
PCWSTR pszVersion = L"v4.0.30319";
ICLRMetaHost* lpMetaHost = NULL;
ICLRRuntimeInfo* lpRuntimeInfo = NULL;
ICorRuntimeHost* lpRuntimeHost = NULL;
_AppDomainPtr spAppDomain = NULL;
BOOL bLoadable = false;
IUnknownPtr spAppDomainThunk = NULL;
CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID *)&lpMetaHost);
// After this line i can "late detect" 6 array bound heap corruptions in process memory.
lpMetaHost->GetRuntime(pszVersion, IID_ICLRRuntimeInfo, (LPVOID *)&lpRuntimeInfo);
lpRuntimeInfo->IsLoadable(&bLoadable);
lpRuntimeInfo->GetInterface(CLSID_CorRuntimeHost, IID_PPV_ARGS(&lpRuntimeHost));
lpRuntimeHost->Start();
lpRuntimeHost->GetDefaultDomain(&spAppDomainThunk);
spAppDomainThunk->QueryInterface(IID_PPV_ARGS(&spAppDomain));
spAppDomainThunk->Release();
// Now I can "late detect" up to 9 array bound heap corruptions in process memory.
return 0;
}
Any ideas on how to avoid this? Currently in some cases it still works, but as my applications gets bigger the chance for an error increases exponentially.