COMException Type Mismatch Error in Microsoft Visual Studio .NET

Updated Apr 4, 2023

Reported In

Software

  • Measurement Studio

Programming Language

  • Visual Basic .NET

Issue Details

I am trying to use the Measurement Studio 6.0 controls in Microsoft Visual Basic 7 or Visual C#. For the function calls that require a variable to be passed by reference, I receive the following error at run-time: 

COMException: Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))

 

Solution

The way to correct this is to assign null to the object every time before using it. Here's an example:

object data=null
axCWDIO1.Ports.Item(0).SingleRead(ref data);
data=null;
axCWDIO1.Ports.Item(0).SingleRead(ref data);







 

Additional Information

This is a common problem that occurs because of the changes that were made to the .NET framework. Visual Basic and Visual C# provide support for interfacing with COM via the System.Runtime.InteropServices libraries. To be able to actually use a COM object with the new framework, you have to use a Runtime Callable Wrapper (RCW), which is created automatically via the IDE or by using the TlbImp.exe utility.

Most of the Measurement Studio controls require a variant pass in by reference (VARIANT *), in effect changing the object type that was passed through.

For example, if we use the RCW to call the CWDIO control's SingleRead method, we have the following:

object data=null
axCWDIO1.Ports.Item(0).SingleRead(ref data);
axCWDIO1.Ports.Item(0).SingleRead(ref data);


The first time this method is called, data is marshalled to the method as a Variant by reference (which is what the method expects) and the method returns correctly.

The next time the same method is called, data is now in a different state (data was passed by reference) into SingleRead. The framework will attempt to pass data by marshalling it in its current state, and this will cause the control to throw a type mismatch exception.