Monday, April 21, 2008

Convert Byte Array 2 Variant Array and reverse

VARIANT ByteArray2VarArray(CByteArray &ba)
{
VARIANT vt;
VariantInit(&vt);
SAFEARRAY *psa;
SAFEARRAYBOUND rgsBounds[1];
rgsBounds[0].lLbound = 0;
rgsBounds[0].cElements = ba.GetSize();
psa = SafeArrayCreate(VT_UI1, 1, rgsBounds);
for (int i = 0; i <>
{
SafeArrayPutElement(psa, (long*)&i, (ba.GetData() + i));
}
vt.vt = VT_ARRAYVT_UI1;

vt.parray = psa;
return vt;

}

bool VarArray2ByteArray(VARIANT var, CByteArray &ba)

{
if ( ! (var.vt & VT_UI1))

{
return false;
}
if ( ! (var.vt & VT_ARRAY))

{
return false;
}
SAFEARRAY* psa;
if (var.vt & VT_BYREF)
{
psa = *(var.pparray);
}
else
{
psa = (var.parray);
}
long lLbound, lUbound;
SafeArrayGetLBound(psa, 1, &lLbound);

SafeArrayGetUBound(psa, 1, &lUbound);
for (long i = lLbound; i <= lUbound; i++)
{
unsigned char b;
if( SafeArrayGetElement(psa, &i, &b) == S_OK)
{
ba.Add(b);
}
}
return true;
}

No comments: