// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
#include <stdio.h>
#include <stdlib.h>

#include <windows.h>
#include <initguid.h>
#include <tchar.h>

#include "Test.h"

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: %s\n", func, buffer);
        exit(1);
    }
}

int main()
{
    HRESULT res;
    CoInitialize(NULL);
    printf("COM/C++ with CoCreateInstance:\n");
    ITest *pTest;
    res = CoCreateInstance(CLSID_CoTest, NULL, CLSCTX_INPROC_SERVER, IID_ITest, (void**)&pTest);
    ReturnCheck(_T("CoCreateInstance"), res);
    long int v;
    res = pTest->Add(123, 456, &v);
    ReturnCheck(_T("Add"), res);
    printf("123 + 345 = %d\n", v);
    BSTR s1 = SysAllocString(L"ABC");
    BSTR s2 = SysAllocString(L"XYZ");
    BSTR s3;
    res = pTest->Concat(s1, s2, &s3);
    ReturnCheck(_T("Concat"), res);
    printf("%d %ls + %d %ls = %d %ls\n", SysStringLen(s1), s1, SysStringLen(s2), s2, SysStringLen(s3), s3);
    SysFreeString(s1);
    SysFreeString(s2);
    SysFreeString(s3);
     pTest->Release();
    CoUninitialize();
    return 0;
}
