views:

355

answers:

2

We are working with an existing native application (most likely written in VB) that loads assemblies and calls methods with "Late Binding." We do NOT have access to its source code.

We want to implement this interface in C#, and have the native application call our C# assembly.

Is this something that's possible?

Is this anything we have to do beyond matching the method names and method signatures to make it work?

+1  A: 

If you're trying to call .NET code from VB6 the cleanest way would be to make the C# code appear as a COM object to the VB6 code - so yes, you would need to mark your C# code as ComVisible and ensure that it looks like the existing COM interface.

Update: Here's an article to get you started.

Vinay Sajip
We are working with an existing application that is already written and we do not have the source code to. It uses late-binding to open an object of specific name and call methods of a specific name. I am wondering if such an object can be implemented in C#, I would expect that VB might not be able to load .Net objects in this manner. You do know what the term "late binding" refers to?
Jonathan.Peppers
Sure, in the COM world late binding means IDispatch. You are asking if a C# implementation for an existing COM interface is possible, and the answer would be yes if you implement carefully.
Vinay Sajip
Is there a good article explaining how to do so?
Jonathan.Peppers
A: 

These are the steps required to make it work:

  1. Mark your class [ComVisible(true)], and make sure to give it a unique [Guid] attribute
  2. Match your ProgId to your class which is normally MyNamespace.MyClass, but you can add an attribute on your class to override this as well
  3. Put the proper [DispId] attributes for each method that will be called
  4. Compile your assembly and run regasm.exe on your assembly

And voila! Native code can call your C# via "late binding". I, of course, had to setup several registry keys to make my native applciation know how to load my assembly, but all is working.

Jonathan.Peppers
So what was wrong with my answer, other than I didn't lay it out step by step for you? I did point you to a relevant article, right?
Vinay Sajip
Is mine not the best answer?
Jonathan.Peppers
But you asked the question in the first place, so presumably you didn't have the answer at that point. It's normal to credit people who have helped you reach the final answer with upvoting and/or acceptance; it's not normally the case you'll get a complete ready-to-use answer with Is dotted and Ts crossed on a plate. Of course you can fill in the last details and create your own answer and accept that - your answer will be exactly what you wanted, and so in that sense "the best". But it seems to me contrary to the spirit of Stack Overflow for people to accept their own answers.
Vinay Sajip