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.开发者_如何学JAVA
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.?
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.
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.
精彩评论