Microsoft KB Archive/327110

= BUG: Calling COM Methods with ByRef Object Array Parameter from .NET Fails with InvalidCastException =

Article ID: 327110

Article Last Modified on 2/23/2007

-

APPLIES TO


 * Microsoft .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 &quot;More Information&quot; 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.



Steps to Reproduce the Behavior
 Use Microsoft Visual Basic 6.0 Project Wizard to create an ActiveX DLL project.  Copy the following code to Class1: Public Function Moo(ByRef Ary As Object) Set Ary(0) = Nothing Moo = Ary MsgBox &quot;Done&quot; End Function  Make Project1.dll. Create a new Visual Basic .NET Console Application. Add a reference to Project1.dll.  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 </li> Press F5 to run the application.</li></ol>

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.

Keywords: kbbug kbnofix KB327110

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.