views:

265

answers:

2

Hi

I have my project developed in MFC which is unmnaged code. Now i need to create a similar application in C#, by reusing most of the MFC classes.

Is it possible to directly export class/struct/enum from MFC dll, so that i can import it in my C# using dllimport and use it.?

+3  A: 

Yes, it is quite possible. You just need to be careful with the types. Many translate very nicely but some are quirky.

The name of the concept you're searching for is COM interop. See here for a getting started tutorial. Of course, the MFC DLL has to support COM to be accessible from .NET. You need to rebuild your MFC DLLs with the proper COM interfaces supported.

Here is an MSDN overview of COM Automation complete with links to sample projects.

And here is a simple but to-the-point CodeProject sample that demonstrates exactly how COM DLLs can be used from within .NET assemblies.

Great pinvoke reference here. For accessing native Win32 APIs as well.

Edit: Another Idea

In case you cannot rebuild your MFC DLLs (you don't have the source or the right version of the IDE) you can create a COM "wrapper" DLL in MFC or raw C/C++ which would import the MFC DLLs in the standard, pre-COM manner and then expose the objects and methods that you need.

Paul Sasik
Thank you very much for the info. The problem for me is, i am not able to add reference to the MFC dll which i created as mentioned in "getting started tutorial.". It says, the dll is not a valid COM component.
Harsha
Ah, ok. In that case you have to rebuild your MFC DLLs and make them COM-usable, if think this means turning on the Automation flag for the build (it's been many years since MFC for me.) When you rebuild your MFC DLLs will have COM-accessible interfaces ready for use in .NET
Paul Sasik
@Harsha: i added som COM Automation info into the body of the original answer. Take another look.
Paul Sasik
Surely it is also possible to do via a mixed mode C++ assembly, which you can then call from your C# dll, thus avoiding the whole COM thing? I've done it this way several years ago, but i wasn't calling MFC, so maybe this idea won't fly. And maybe mixed mode has moved on or morphed a little since VS2005 days?
slugster
+1  A: 

You cannot [DllImport] MFC classes, it only works for static functions. Turning them into COM coclasses is only technically possible, the surgery is major. The best way to do this is by writing managed class wrappers in the C++/CLI language. You'd write a ref class for every MFC class. It stores a pointer to the MFC class object, every method directly calls the corresponding MFC class method. In the vast majority of cases that's one line of code.

It is a very mechanical process, you can use SWIG to do the job for you. Not sure how good it is, never used it myself.

A decent tutorial on C++/CLI and the wrapper approach is available here.

Hans Passant