I have a C# dll exposed to vb6 via com-interop. This is all working, but I am noticing something strange when I pass an array of a custom objects from .Net into VB6.
Accessing the array from VB6 is what baffles me. If I access the array directly I have to do it like this:
Dim manager as New ObjectManager
'Access with two sets of parentheses:
msgbox manager.ReturnArrayOfObjects()(0).Name
However, if I copy the array first I can access it how I would normally expect to:
Dim manager as New ObjectManager
Dim objectArray() As CustomObject
'copy the array
objectArray = manager.ReturnArrayOfObjects
'access normally:
msgbox objectArray(0).Name
In the first case I had to use two sets of parentheses: manager.ReturnArrayOfObjects()(0).Name
In the second case I could just use one set of parentheses: objectArray(0).Name
Does anyone know why this is the case? Am I doing something wrong here with the interop maybe?
Here is a quick stub/sample of the C# interop code.
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[Guid("[Guid here...]")]
public interface IObjectManager
{
[DispId(1)]
CustomObject[] ReturnArrayOfObjects();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("[guid here...]")]
public class ObjectManager: IObjectManager
{
public CustomObject[] ReturnArrayOfObjects()
{
return new CustomObject[] { new CustomObject(), new CustomObject() };
}
}
The class CustomObject()
is also exposed to com-interop and working just fine. Please let me know if you need me to post anymore code, but I think these little snippets represent the problem well enough to begin with.
Thanks in advance for your help.
ReturnArrayOfObjects()
in the C# code is a method. Your VB6 code is invoking the method, which returns the array, and then accessing the first element. The difference between this
msgbox manager.ReturnArrayOfObjects()(0).Name
and this
objectArray = manager.ReturnArrayOfObjects
msgbox objectArray(0).Name
Is that in the second, you invoke the method by itself without accessing the first element, and VB is allowing you to leave off the parentheses from the method call. Conversely, the language is not allowing you to leave off the parentheses when you directly access the first element. It's simply a language feature, it's not a "double parentheses array syntax" issue.