tags:

views:

1893

answers:

2

I need to return an array of initialized objects from VB6 into C# using interop. My VB function looks like

Public Function CreateMyObjArray(ByVal MaxCount As Integer) As MyObj()

  Dim i As Integer
  Dim temparray() As MyObj
  ReDim temparray(MaxCount) As MyObj

  For i = 0 To MaxCount
      Set temparray(i) = New MyObj
  Next i

  CreateMyObjArray = temparray

End Function

Now, when I call this from C# after passing in the array by

Array InData = m_MyObjGenerator.CreateMyOjbArray(5);

I get a system.argumentexceptionerror where the message is

"Exception of type 'System.ArgumentException' was thrown.\r\nParameter name: typeName@0"

I also get this error if my function has no parameters. The function works in VB from a form. Likewise, the following function returns a MyObj just fine

Public Function CreateMyObj() As MyObj
 Set CreateMyObj = New MyObj
End Function

I know I can make a list of new MyObj's in the C# version and then .ToArray() it, but I would really like to get this working. Thanks.

Solution Found out how to do it. I had to use tlbimp.exe without the /sysarray flag (which VS must use internally). After that, I was able to get everything working correctly. Thanks for the help guys.

+3  A: 

I am sorry that I can't try out some code to really help you solve this.

Having said that, set InData to be an Object.
Object InData = m_MyObjGenerator.CreateMyOjbArray(5);

After that statement executes, use the watch window to determine the type of InData.
Modify the code (change the type of InData from Object to the type that you discovered using the watch window).

Hope that helps.

shahkalpesh
+1, This should always be the first attempt.
erikkallen
+1  A: 

First off let's clean up that VB a bit:

Public Function CreateMyObjArray(ByVal MaxCount As Integer) As MyObj()     
  ''// MaxCount = 5 would allocate 6 array items with your old code
  ''// Also: do this in one line rather than with an expensive "ReDim"
  Dim temparray(MaxCount-1) As MyObj 

  Dim i As Integer
  For i = 0 To MaxCount -1 
      Set temparray(i) = New MyObj
  Next i

  CreateMyObjArray = temparray
End Function

Finally, you C# should look like this:

MyObj[] InData = m_MyObjGenerator.CreateMyObjArray(5);

Where MyObj is the marshalled type use when talking to your vb code. As another poster suggested, you can set it to Object and step to it to let Visual Studio tell you what type to use exactly.

Joel Coehoorn
VS is importing it as system.array, your second code snippet leads to a compiler error. Thanks for the help.
Steve
Yes, I wouldn't expect it to compile, because "MyObj" is just a placeholder for your real type. To get past the System.Array, try using Object[] there and then get visual studio to tell you the type of one element in the array.
Joel Coehoorn