How do you return an struct or class from a .NET COM dll to a consuming VB6 application?
See the question and my original answer on StackOverflowThere are not only one way to make this work, but here is a simple one that matches how you're doing things:
C# code can be very simple, you don't need to declare interfaces explicitely, you don't need to use ref
keyword everywhere, etc, but you do need to add a ComVisible(true)
attribute to your classes (string, int, etc. are implicitely ComVisible):
[ComVisible(true)]
[ProgId("One.Two.Three.SomeClass")]
public class SomeClass1
{
public SomeClass2 SomeFunction(string text)
{
return new SomeClass2 { Text = text };
}
}
[ComVisible(true)]
public class SomeClass2
{
public string Text { get; set; }
}
VB/VBA code:
Dim result As Object
Dim someObj
Set someObj = CreateObject("One.Two.Three.SomeClass")
' note the "Set" keyword, it's mandatory for COM objects...
Set result = CallByName(someObj, "SomeFunction", VbMethod, "hello world")
MsgBox result.Text
But, if you want to get Intellisense from VB/VBA, you can also declare the classes like this:
// progid is now optional because we won't need CreateObject anymore
[ProgId("One.Two.Three.SomeClass")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class SomeClass1
{
public SomeClass2 SomeFunction(string text)
{
return new SomeClass2 { Text = text };
}
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class SomeClass2
{
public string Text { get; set; }
}
I've just added ClassInterfaceType.AutoDual
, and now I can reference a TLB (that I created using regasm /tlb), and use this code in VB/VBA:
Dim c1 As New SomeClass1
Set c2 = c1.SomeFunction("hello world")
MsgBox c2.Text
ClassInterfaceType.AutoDual
is not "recommended" because if you go that route, you'll have to make sure the binaries between the COM client (here VB/VBA) and the COM server (here C#) are 100% in sync or you may suffer hard VB/VBA crashes. However, it's a compromise, intellisense is a great productivity tool IMHO.
One last word on returning List<T>
, you'll have troubles with that. If you face it, ask another question :-)