Search code examples
c#comvb6com-interopvb6-migration

How can I share an interface between VB6 and C#?


I would like to be able to code a class interface which I can implement in C# and VB6 classes so that these classes can be handled in the same way within VB6 code but I can't make this work.

In VB6 I want to have come class VB6Class using the Implements key word to implement some interface ISharedInterface.

In C# I want to have some other class C#Class which I can expose to COM as also implementing ISharedInterface.

The goal is that VB6 code will then be able to operate on VB6Class and C#Class via ISharedInterface without caring which language the classes were built in.

I want to use this technique as a way to migrate away from VB6 by successively rewriting everything at the VB6 end and if I can implement interfaces I already have in VB6 within C# this would be ideal. But failing that, even if I have to rewrite an interface in C# to share back to VB6 that would still be useful (i.e. I don't even care whether the interface is written in C# and exposed to COM or written in COM and consumed by C#, so long as both sides of the language barrier can reference the same interface).

I'm finding this surprisingly hard. I can reference an interface in C# that comes from COM but I can't export it back to COM as a COM visible interface. If, as an alternative, I try to create an interface in C# itself I haven't found a way to see it directly over COM and various workarounds I have tried to use it indirectly, like creating a stub class to implement the interface and exposing that as COM visible just raise run time errors in VB6 when I try to implement the exposed stub class (even though they compile).

I currently have no good solution for this and only a horribly clunky work around which is to implement separate interfaces in C# and VB6, expose the C# methods directly to COM and create a wrapper class in VB6 that simply redirects the interface methods to the underlying true methods.

What is the best way to create a single interface (either in VB6 or C#) which both languages can reference without me having to duplicate the interface definition?


Solution

  • What is the best way to create a single interface (either in VB6 or C#) which both languages can reference without me having to duplicate the interface definition?

    Write the interface in IDL and compile into a type lib which is referenced in VB and imported (tlbimp) into .NET. (You need to avoid the regeneration of IIDs that VB6 will do if you use it to define the interface.)

    You could define the interface in .NET, but that would involve more steps.