0

I've never worked with variants in C++. But I'm maintaining code from old C++ projects. Part of it is to translate it or part of it into C#.

I found methods that use variants. I want to "kill" any variant use in a new project version. Can someone help me out on how? Based on this example maybe? Also I'm not a C++ expert. I would like to know what this method is doing (Obviously converting variant to byte array. But how exactly? Where is the data etc.?)

(Example) Method:

protected bool ConvertVariantToByteArray(VARIANT vtData, int lCount, BYTE[] pArray)
{
    if (vtData.vt != (VARENUM.VT_ARRAY | VARENUM.VT_UI1))
        return false;
    BYTE[] pSafeArrayData;
    if (FAILED(SafeArrayAccessData(vtData.parray, (void**) &pSafeArrayData)))
    {
        return false;
    }
    long lLbound;
    if (FAILED(SafeArrayGetLBound(vtData.parray, 1, &lLbound)))
    {
        SafeArrayUnaccessData(vtData.parray);
        return false;
    }
    long lUbound;
    if (FAILED(SafeArrayGetUBound(vtData.parray, 1, &lUbound)))
    {
        SafeArrayUnaccessData(vtData.parray);
        return false;
    }
    if (lCount < lUbound - lLbound + 1)
    {
        lCount = lUbound - lLbound + 1;
        SafeArrayUnaccessData(vtData.parray);
        return false;
    }
    for (long i = lLbound; i < lUbound + 1; ++i)
    {
        *pArray++ = *pSafeArrayData++;
    }
    SafeArrayUnaccessData(vtData.parray);
    lCount = lUbound - lLbound + 1;
    return true;
}

Larger context:

The application reads/writes via Falcon library to/from EIB/KNX bus. Seems the data passed to/from the bus is of VARIANT data type.

Bitterblue
  • 13,162
  • 17
  • 86
  • 124
  • 3
    Variants are used with COM objects. If you are using COM, then you may have to use variants. What's the larger context of your question? – Lubo Antonov Feb 23 '15 at 11:33
  • 1
    Did you have a look here? -> http://stackoverflow.com/questions/15806733/variant-datatype-of-c-into-c-sharp – Manuel Barbe Feb 23 '15 at 11:34
  • It mostly corrupts memory, the caller does not have good odds at guessing at the required size of pArray. Do not use it. Converting a variant to byte[] in C# is trivial, just cast it. – Hans Passant Feb 23 '15 at 11:36

1 Answers1

1

VARIANT is a COM thing rather than a C++ thing. You may not need to translate this method verbatim if you are moving away from variants.

A VARIANT can stores (alomst) anything, including other VARIANTS. The code you have shown converts a VARIANT to an array of bytes.

The array has a lower and upper bound (lbound and ubound in this sample) - they do no need to run from 0 up. The for loop is copying the data into the array.

You can call COM from C#, so may not need to translate the code.

doctorlove
  • 18,872
  • 2
  • 46
  • 62