Tuesday, May 02, 2006

.NET FAQ: How .NET Applications Use Unmanaged C++ DLLs with No Source Code?

Currently, I have run into a question regarding how managed code can call unmanaged C++ classes stored in a DLL, without unmanaged source code. The managed code can be in any .NET compliant language, C++, C#, VB, or J#. Lets look at a simple example.
class __declspec(dllexport) Vehicle 
Vehicle(char* idx);
virtual ~Vehicle();
char* GetId() const;
virtual void Move();
char* id;
class __declspec(dllexport) Car : public Vehicle
void Move();

Aassume the two classes were built in a DLL and you don't have the source code. How can your .NET applications use the unmanaged C++ classes stored in this DLL?

In my recent article(here), I've demonstrated a wrapping approach to reusing unmanaged C++ libraries, particularly when direct importing from unmanaged DLLs becomes necessary. I have demonstrated three steps to wrap unmanaged C++ DLLs for use in .NET applications:
1) Retrieve class member data from the DLL.
2) Import required class methods.
3) Wrap up all the imports in a managed class.

The tutorial also showed that the implemention of the approach is not trivial, mainly because you must recover the original relationship between unmanaged classes, such as inheritance, virtual functions and polymorphism. Managed C++ can help, but when there are conflicts, you have to simulate some C++ compiler internals. In working with C++ internals, you will find virtual table and function pointer helpful.