// 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 <windows.h>
#include <initguid.h>
#include <tchar.h>

#import "Test.tlb" no_namespace named_guids

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 constructor:\n");
    try
    {
        ITestPtr spTest(__uuidof(CoTest));
        long v = spTest->Add(123, 456);
        printf("123 + 345 = %d\n", v);
        BSTR s1 = SysAllocString(L"ABC");
        BSTR s2 = SysAllocString(L"XYZ");
        BSTR s3 = spTest->Concat(s1, s2);
        printf("%d %ls + %d %ls = %d %ls\n", SysStringLen(s1), s1, SysStringLen(s2), s2, SysStringLen(s3), s3);
        SysFreeString(s1);
        SysFreeString(s2);
        SysFreeString(s3);
        BSTR sv = spTest->GetSV();
        printf("IV = %d SV = %d %ls\n", spTest->GetIV(), SysStringLen(sv), sv);
        SysFreeString(sv);
        spTest->PutIV(123);
        spTest->PutSV(SysAllocString(L"ABC"));
        sv = spTest->GetSV();
        printf("IV = %d SV = %d %ls\n", spTest->GetIV(), SysStringLen(sv), sv);
        SysFreeString(sv);
        spTest = NULL;
    }
    catch (_com_error er)
    {
        _tprintf("%s\n", er.ErrorMessage());
    }
    CoUninitialize();
    return 0;
}
