Using unmanaged code from managed code

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

Is it possible to directly export the / struct / enum class from an MFC dll so that I can import it into my C # using dllimport and use it.?

+6
c # dll mfc managed unmanaged
source share
2 answers

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

The name of the concept you are looking for is COM interop. See here for a getting started tutorial. Of course, the MFC DLL must support COM for access from .NET. You need to rebuild your MFC libraries with the corresponding supported COM interfaces.

Here is an MSDN Overview for COM Automation with links to sample projects.

And here's a simple but pointy CodeProject example that demonstrates how COM libraries can be used from .NET collections.

Great link here. To access native Win32 APIs as well.

Edit: another idea

If you cannot restore your MFC DLLs (you do not have the original or correct version of the IDE), you can create a COM shell DLL wrapper in MFC or raw C / C ++ that will import the MFC DLLs into the standard one, before COM -method, and then expose the objects and methods that you need.

+5
source share

You cannot [DllImport] MFC classes, it only works for static functions. Inclusion of them in COM-classes is only technically possible, surgery is the main one. The best way to do this is to write managed class wrappers in C ++ / CLI. You must write a ref class for each MFC class. It stores a pointer to an object of the MFC class, each method directly calls the corresponding method of the MFC class. In the vast majority of cases, one line of code.

This is a very mechanical process, you can use SWIG to do this job. Not sure how good he is, never used it myself.

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

+3
source share

All Articles