// 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);
        ITestPtr another = spTest->Another();
        printf("Another 123 + 345 = %d\n", another->Add(123L, 456L));
        another = NULL;
        spTest = NULL;
        ITestPtr temp(__uuidof(CoTest));
        ITest2Ptr spTest2 = temp;
        printf("SUM = %d\n", spTest2->Sum(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
        printf("SUM 1..5 = %d\n", spTest2->Sum(1, 2, 3, 4, 5, 0, 0, 0, 0, 0));
        printf("SUM 1..10 = %d\n", spTest2->Sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
        spTest2 = NULL;
        temp = NULL;
    }
    catch (_com_error er)
    {
        _tprintf("%s\n", er.ErrorMessage());
    }
    CoUninitialize();
    return 0;
}
