I am pretty new to managed/unmanaged interoperability and COM concepts.
I received a suggestion of using COM Interop, for using my existing MFC code in C#. But the problem for me is, i have a MFC Dll which is not a valid COM component. How can I make this MFC DLLs to have COM-accessible interfaces ready for use in .NET?
Of the three ways to call native code from managed code (COM Interop, P/Invoke, and IJW or C++/CLI interop), COM Interop is the slowest. And if your existing native code is not in the form of a COM component, then it's also the hardest because that will be step 1.
To use P/Invoke you will need some C-style functions (extern C) that go on and call your existing code. To use IJW or C++/CLI interop you will implement a
public ref
class (in a file compiled /clr) with methods that go on and call your existing code. It is up to you which you find easier. Once you have the wrapper, from C# you can do the PInvoke with aDllImport
attribute on the declaration of the functions, and you then call them as usual. To do the IJW you add a reference to the assembly with the public ref class in it and call the methods on that class as usual.My recommendation is to ask whether you want some sort of Facade pattern where you're putting some logic in front of the interop - if so, go IJW. Also if you want to control the marshaling, go IJW. If not then go P/Invoke. But either way works.
There is no simple way to make MFC Dll COM accessible. It is necessary to write a lot of COM code manually, making COM wrapper. If you don't have previous COM experience, this may be difficult. The second option from Jacob Seleznev's post looks less painful. C++/CLI wrapper which is internally linked to existing MFC dll, and exposes pure .NET interface to C# client, looks like optimal solution.
If MFC Dll exports C-style interface (API), and not classes, use PInvoke.
From my experience, I concur with @Jacob Seleznev and will add that if your MFC DLL interface contains mainly "simple" parameter and return types, using the DLLImportAttribute is most likely going to be your path of least resistance.
A great reference for marshaling types is to see how it's done against the unmanaged Win32 API. That can be found here: pinvoke.net
What I've done is find an API call with like types and see how that call is setup on pinvoke.net. I don't use it often anymore, but it was extremely helpful a few years ago.
Hope this helps.
From thread Loading MFC DLL in C# Windows Application