Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

VariantChangeTypeEx (oleaut32)
 
.

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

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions