// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
// standard
#include <iostream>
#include <cstdio>
using namespace std;

// Windows
#include <windows.h>
#include <tchar.h>

// .NET
#include <MSCorEE.h>
#include <MetaHost.h>
#pragma comment(lib, "mscoree.lib") 

void ReturnCheck(LPTSTR func, HRESULT res)
{
    if(res != S_OK)
    {
        TCHAR buffer[1000];
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, res, 0, buffer, sizeof(buffer), 0);
        _tprintf("%s: %d = %08X = %s\n", func, res, res, buffer);
        exit(1);
    }
}

int main()
{
    HRESULT hr;
    DWORD dwRet;
    ICLRRuntimeHost *pClrHost;
    ICLRMetaHost *lpMetaHost;
    ICLRRuntimeInfo *lpRuntimeInfo;
    hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&lpMetaHost));
    ReturnCheck("CLRCreateInstance", hr);
    hr = lpMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&lpRuntimeInfo));
    ReturnCheck("GetRuntime", hr);
    hr = lpRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID *)&pClrHost);
    ReturnCheck("GetInterface", hr);
    hr = pClrHost->Start();
    ReturnCheck("Start", hr);
    hr = pClrHost->ExecuteInDefaultAppDomain(L"Test.dll", L"N2M.TestClass", L"TestMethod", L"ABC", &dwRet);
    ReturnCheck("ExecuteInDefaultAppDomain", hr);
    cout << "C++ got " << dwRet << " back" << endl;
    hr = pClrHost->Stop();
    ReturnCheck("Stop", hr);
    hr = pClrHost->Release();
    ReturnCheck("Stop", hr);
    return 0;
}
