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 
{
public:
Vehicle(char* idx);
virtual ~Vehicle();
char* GetId() const;
virtual void Move();
protected:
char* id;
};
class __declspec(dllexport) Car : public Vehicle
{
public:
~Car();
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.

4 Comments:

Blogger Charles Halfpenny said...

Great article. Can this method also be used on unmanaged code provided as a library? I tried running dumpbin on the .lib file but did not get ordinal information. I do have a c++ header file with all the function descriptions, would this be helpful?

12:53 PM  
Blogger Charles Halfpenny said...

Great article. Can this method also be used on unmanaged code provided as a library? I tried running dumpbin on the .lib file but did not get ordinal information. I do have a c++ header file with all the function descriptions, would this be helpful?

ch@halfpenny.com

12:53 PM  
Blogger Fang said...

Really good article, very useful. But when I followed the idea discussed in this article, I met two problems: 1) when I use dumpbin to export my dll file, it does not fully dump all of functions out. Why? 2)How to deal with callback?

9:45 AM  
Blogger Shawn Liu said...

Nice article, especially you published it back in 2006. I wrote a tool to automate the whole thing and resolved a lot of other issues with calling C++ class from C#. You can read my blog here.

C# Wrapper Generator for C++ DLL

1:22 PM  

Post a Comment

<< Home