Search code examples
c++structcomvariant

How to convert user-defined struct to variant in c++?


I have a struct in native c++, which should be passed to a COM object; both share same header file and hence there is no difference in struct definition between the COM object and my code. The COM method expects a pointer to struct as parameter. I am able to pass types like int, float, string, etc as parameters to COM by converting them to variant like variant_t vtArg(myIntValue).

How do I convert struct to variant?

The signature of the COM method is like this:

bool ComMethod(HANDLE *myHandle, MyStruct *myStruct)

This is how I construct arguments for the COM method:

SAFEARRAY *pMethodArgs = SafeArrayCreateVector(VT_VARIANT, 0, 2);
LONG index = 0;    
SafeArrayPutElement(pMethodArgs, &index, &myHandle);
index = 1;
SafeArrayPutElement(pMethodArgs, &index, &myStruct);

Solution

  • I tried multiple ways and found that it is not possible to send MyStruct as parameter. I made the COM method return an instance of MyStruct and tried to reverse-engineer the return value in C++, but unfortunately nothing was received at C++.

    The solution is to create a SAFEARRAY of VARIANT with individual members of the structure, or to pass the individual members as separate parameters.