// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
// standard C++
#include <cstring>
#include <cstdlib>

// standard .NET
#using <mscorlib.dll>
using namespace System;
using namespace System::Runtime::InteropServices;

// the C functions
extern "C"
{
#include "demolib.h"
}

// the data classes
#using "MgData.dll"

// class with wrapper methods
public ref class Mix
{
    public:
        static int MixAdd(int a, int b);
        static int MixSum(array<int>^ a);
        static String^ MixDup(String^ s);
        static void MixGetOut([out] int% iv, String^% sv);
        static MgData1 MixGetRet();
        static void MixChg(MgData2% d);
};

int Mix::MixAdd(int a, int b)
{
    return add(a, b);
}

int Mix::MixSum(array<int>^ a)
{
    pin_ptr<int> p = &a[0];
    return sum(a->Length, p);
}

String^ Mix::MixDup(String^ s)
{
    IntPtr p = Marshal::StringToHGlobalAnsi(s);
    char *s1 = static_cast<char *>(p.ToPointer());
    char *s2 = dup(s1);
    String^ res = gcnew String(s2);
    Marshal::FreeHGlobal(p);
    free(s2);
    return res;
}

void Mix::MixGetOut(int% iv, String^% sv)
{
    int tempiv;
    char *tempsv;
    get_out(&tempiv, &tempsv);
    iv = tempiv;
    sv = gcnew String(tempsv);
    free(tempsv);
}

MgData1 Mix::MixGetRet()
{
    Data1 *d = get_ret();
    MgData1 res;
    res.iv = d->iv;
    res.sv = gcnew String(d->sv);
    return res;
}

void Mix::MixChg(MgData2% d)
{
    struct Data2 nd;
    nd.iv1 = d.iv1;
    IntPtr p = Marshal::StringToHGlobalAnsi(d.sv1);
    strcpy(nd.sv1, static_cast<char *>(p.ToPointer()));
    Marshal::FreeHGlobal(p);
    chg(&nd);
    d.iv2 = nd.iv2;
    d.sv2 = gcnew String(nd.sv2);
}
