variantchangetypeex (oleaut32)
Last changed: -80.61.160.102

.

Changes an oleautomation variant (.NET an object) to a specific oleautomation compliant type, e.g. VT_BSTR (vbString) .

Very handy to convert a reference to a Dispatch interface to a string (which is in fact the result of recursive Invoke(s) to the DISPID(0).

If you write a COM interface which will be used by Javascript or Vbscript, you really need this function. Automation variables are very difficult to manage and they are passed by reference (VT_BYREF) or as Dispatch (VT_DISPATCH) or as a number while you just need, e.g. a string.

C# Signature:

[DllImport("oleaut32.dll", SetLastError = false, ExactSpelling = true)]

    private extern static int VariantChangeTypeEx([MarshalAs(UnmanagedType.Struct)]out object pvargDest,
           [In, MarshalAs(UnmanagedType.Struct)] ref object pvarSrc, int lcid, short wFlags,[MarshalAs(UnmanagedType.I2)] short vt);

VB Signature:

Declare Function VariantChangeTypeEx Lib "oleaut32.dll" (TODO) As TODO

User-Defined Types:

None.

Alternative Managed API:

The alternative would be lots of invokes on an imported IDispatch interface if the source type is an object (Dispatch) and lots of conversion checks. Some of them could be converted using Convert.ToString(), however Convert.ToString() would not deal with Dispatch types.

Notes:

See also VarBstrFromDisp

Tips & Tricks:

There is a lot to write about automation variables. E.g. a parameter can be optional and thus, have a default value which is in the TYpeLib. Or VT_ERROR | DISP_E_PARAMNOTFOUND (which is equivalent to VarType() = vbMissing). This is passed to .NET as Type.Missing. See sample code.

Sample Code:

if (!(OptionValue is DBNull) && !(OptionValue == Type.Missing))

{

    object Conv;
     int hr = VariantChangeTypeEx(out Conv, ref OptionValue, Thread.CurrentThread.CurrentCulture.LCID, 0, (short)VarEnum.VT_BSTR);
      if (hr != 0)
     {
    Marshal.ThrowExceptionForHR(hr);
     }
     else
     {
     vOptionalValue = (string)Conv;
     }

}

Documentation