BUG: Calling COM Methods with ByRef Object Array Parameter from .NET Fails with InvalidCastException (327110)



The information in this article applies to:

  • Microsoft Windows .NET Framework 1.1
  • Microsoft .NET Framework 1.0

This article was previously published under Q327110

SYMPTOMS

When you call a Component Object Model (COM) method with the ByRef Object Array parameter from a Microsoft .NET application, the .NET runtime generates the following exception:
Unhandled Exception: System.InvalidCastException: Specified cast is not valid.

RESOLUTION

You can pass the array as a ByVal parameter as shown in the sample in the "More Information" section of this article.

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

MORE INFORMATION

Steps to Reproduce the Behavior

  1. Use Microsoft Visual Basic 6.0 Project Wizard to create an ActiveX DLL project.
  2. Copy the following code to Class1:
    Public Function Moo(ByRef Ary() As Object)
        Set Ary(0) = Nothing
        Moo = Ary
        MsgBox "Done"
    End Function
    					
  3. Make Project1.dll.
  4. Create a new Visual Basic .NET Console Application.
  5. Add a reference to Project1.dll.
  6. Relace the entire module, Module1, with the following code:
    Module Module1
        Sub Main()
            Dim objs(9) As Object
            Dim dispArray(9) As System.Runtime.InteropServices.DispatchWrapper
            Dim i As Integer
    
            For i = 0 To 9
                objs(i) = New Exception()
                dispArray(i) = New System.Runtime.InteropServices.DispatchWrapper(objs(i))
            Next
    
            Dim Obj As New Project1.Class1()
            objs = Obj.Moo(CType(dispArray, Object()))	'This works and behaves as Byval.
            Console.WriteLine(TypeName(dispArray(0).WrappedObject))
    
            objs = Obj.Moo(dispArray)		'The exception occurs here. - BUG
            Console.WriteLine(TypeName(dispArray(0)))
        End Sub
    End Module
    					
  7. Press F5 to run the application.
The first call works as expected because the array is passed as ByVal. During the second call, you get the following exception:
Unhandled Exception: System.InvalidCastException: Specified cast is not valid.

Modification Type:MinorLast Reviewed:5/28/2003
Keywords:kbbug kbnofix KB327110