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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.