In fact, this has always been an unsolved problem. The best way is to write the C ++ class library as COM.
But sometimes it is not possible to do this. There are only two methods: convert to the C function form or manage C ++ encapsulation.
The two methods are described below.
Original: http://www.codeproject.com/KB/cs/marshalCPPclass.aspx
Introduction
I recently needed to your Al some legacy C ++ classes into a C # project on which I was working. microsoft provides well known ented means to operate al C-functions, and to operate Al COM components, but they left out a mechanic to operate al C ++ classes. this article documents the discoveries I made and the eventual solution I came up.
Audience
This article assumes the reader is knowledgeable in C # And. NET and is already familiar with pinvoke and logging aling.
Article
I had existing (unmanaged) C ++ DLLs which needed to be used with a managed C # project I was working on. although I had access to the source code of the DLLs, one of the requirements was that the C ++ source code and DLLs cocould not be dramatically altered. this was due to manage reasons, including backwards compatibility with existing projects, the Code having already been QA 'ed, and project deadlines, so converting the original DLLs to be managed C ++ DLLs, or converting the classes within the original DLLs to be COM components was out.
Upon first investigating this issue, I was hoping to be able to declare a definition for a C # version of the class and marshal the object back and forth between the managed and unmanaged memory spaces, similar to how a structure is stored aled back and forth. unfortunately, this is not possible; in my research I discovered that unmanaged C ++ classes can't be passed aled and that the best approach is to either create bridge/wrapper C-functions for the public methods of the class and marshal the functions, or to create a bridge DLL in managed C ++.
Solution A: Create Bridge functions in C and use pinvoke
Suppose we have the following unmanaged C ++ class:
Collapse
class EXAMPLEUNMANAGEDDLL_API CUnmanagedTestClass{public: CUnmanagedTestClass(); virtual ~CUnmanagedTestClass(); void PassInt(int nValue); void PassString(char* pchValue); char* ReturnString();};
Running dumpbin on the DLL containing the class yields the following results:
(Click for larger view. We'll cover the results from dumpbin in a moment ).
Since the instantiation of a C ++ class object is just a pointer, we can use C #'sIntPtr
Data Type to pass unmanaged C ++ objects back and forth, but C-functions need to be added to the unmanaged DLL in order to create and dispose instantiations of the class:
Collapse
// C++:extern "C" EXAMPLEUNMANAGEDDLL_API CUnmanagedTestClass* CreateTestClass(){ return new CUnmanagedTestClass();}extern "C" EXAMPLEUNMANAGEDDLL_API void DisposeTestClass( CUnmanagedTestClass* pObject){ if(pObject != NULL) { delete pObject; pObject = NULL; }}
Collapse
// C#:[DllImport("ExampleUnmanagedDLL.dll")]static public extern IntPtr CreateTestClass();[DllImport("ExampleUnmanagedDLL.dll")]static public extern void DisposeTestClass(IntPtr pTestClassObject); IntPtr pTestClass = CreateTestClass();DisposeTestClass(pTestClass);pTestClass = IntPtr.Zero; // Always NULL out deleted objects in order to prevent a dirty pointer
This allows us to pass the object back and forth, but how do we call the methods of our class? There are two approaches to accessing the methods. The first approach is to use pinvoke and to useCallingConvention.ThisCall
. If you go back to the output from dumpbin, you will see the mangled name forPassInt()
Method is "? Passint @ cunmanagedtestclass qaexh @ Z ". UsingCallingConvention.ThisCall
, The pinvoke definitionPassInt()
Is:
Collapse
[DllImport("ExampleUnmanagedDLL.dll", EntryPoint="?PassInt@CUnmanagedTestClass@@QAEXH@Z", CallingConvention=CallingConvention.ThisCall)]static public extern void PassInt(IntPtr pClassObject, int nValue);
The second approach is to create C-functions which act as a bridge for each public method within the DLL...
Collapse
// C++:extern "C" EXAMPLEUNMANAGEDDLL_API void CallPassInt( CUnmanagedTestClass* pObject, int nValue){ if(pObject != NULL) { pObject->PassInt(nValue); }}...
... And each Al each of new c-functions in C #...
Collapse
// C#:[DllImport("ExampleUnmanagedDLL.dll")]static public extern void CallPassInt(IntPtr pTestClassObject, int nValue);...
I chose to go with the second approach; the name mangling the compiler does means that the first approach is susceptible to breaking if a different compiler is used to compile the C ++ DLL (newer version, different vendor, etc ...), or if additional methods are added to the class. there is a little extra work involved with the second approach, but I feel the extra work is rewarded by having better maintainable code and code which is less likely to break in the future.
At this point I shocould point out that I added the Bridge functions to the original DLL and recompiled the DLL, but what if the DLL in question is a third party DLL and you don't have access to the sources so you can't recompile the DLL (you only have the rights to redistribute it)? In this scenario I suggest either:
- Creating a New DLL in unmanaged C and place the Bridge functions within the new DLL.
- Create a managed C ++ DLL and have it act as the bridge between the C # code and the unmanaged C ++ classes (see solution B further on ).
At this point, the C # code to call our c ++ class looks like:
Collapse
// C#:IntPtr pTestClass = CreateTestClass();CallPassInt(pTestClass, 42);DisposeTestClass(pTestClass);pTestClass = IntPtr.Zero;
This is fine as it is, but this isn't very object-oriented. Suppose you aren't the only one working on the project? Will other clients of your code remember to dispose the C ++ class objectDisposeTestClass()
? Will they correctly useIntPtr
Created fromCreatetestClassDLL()
And not some otherIntPtr
? The next step is to wrap our C # code and pinvoke definitions into a class.
During my investigation, I came authentication ss the following newsgroup posting...
Http://groups.google.com/group/microsoft.public.dotnet.framework.interop/ browse_thread/thread/d4022eb907736cdd/0e74fa0d349479? Lnk = GST & Q = C % 2B % 2B + Class & rnum = 6 & HL = en #0e74fa0d34947251
... And I decided to mirror this approach and create a class in C # calledCSUnmanagedTestClass
:
Collapse
// C#:public class CSUnmanagedTestClass : IDisposable{ #region PInvokes [DllImport("TestClassDLL.dll")] static private extern IntPtr CreateTestClass(); [DllImport("TestClassDLL.dll")] static private extern void DisposeTestClass(IntPtr pTestClassObject); [DllImport("TestClassDLL.dll")] static private extern void CallPassInt(IntPtr pTestClassObject, int nValue); . . . #endregion PInvokes #region Members private IntPtr m_pNativeObject; // Variable to hold the C++ class's this pointer #endregion Members public CSUnmanagedTestClass() { // We have to Create an instance of this class through an exported // function this.m_pNativeObject = CreateTestClass(); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool bDisposing) { if(this.m_pNativeObject != IntPtr.Zero) { // Call the DLL Export to dispose this class DisposeTestClass(this.m_pNativeObject); this.m_pNativeObject = IntPtr.Zero; } if(bDisposing) { // No need to call the finalizer since we've now cleaned // up the unmanaged memory GC.SuppressFinalize(this); } } // This finalizer is called when Garbage collection occurs, but only if // the IDisposable.Dispose method wasn't already called. ~CSUnmanagedTestClass() { Dispose(false); } #region Wrapper methods public void PassInt(int nValue) { CallPassInt(this.m_pNativeObject, nValue); } . . . #endregion Wrapper methods}
Now, the C # client of this Code simply does:
Collapse
// C#:CSUnmanagedTestClass testClass = new CSUnmanagedTestClass();testClass.PassInt(42);testClass.Dispose();
Solution B: create a bridge DLL in managed C ++
Another option is to leave the original DLL untouched and create a new DLL in managed C ++ to act as a bridge between the managed C # code and the unmanaged C ++ classes in the unmanaged DLL. usingCUnmanagedTestClass
Within the managed DLL wasn't difficult, and pinvoke definitions weren't required, but the managed C ++ syntax and classes which needed to be used was a bit vexing:
Collapse
// MCPP:// Forward declariationclass CUnmanagedTestClass;public ref class CExampleMCppBridge{public: CExampleMCppBridge(); virtual ~CExampleMCppBridge(); void PassInt(int nValue); void PassString(String^ strValue); String^ ReturnString();private: CUnmanagedTestClass* m_pUnmanagedTestClass;};CExampleMCppBridge::CExampleMCppBridge() : m_pUnmanagedTestClass(NULL){ this->m_pUnmanagedTestClass = new CUnmanagedTestClass();}CExampleMCppBridge::~CExampleMCppBridge(){ delete this->m_pUnmanagedTestClass; this->m_pUnmanagedTestClass = NULL;}void CExampleMCppBridge::PassInt(int nValue){ this->m_pUnmanagedTestClass->PassInt(nValue);}...
Collapse
// C#:CExampleMCppBridge example = new CExampleMCppBridge();example.PassInt(42);example.Dispose();
(And I have to admit, I'm not very fluent in MCPP)
Pros/CONS
Both approach a and approach B have their own pros and cons. Are you unfamiliar with MCPP? Go with approach a and create C-functions to wrap the public methods of the class and use pinvoke. Can't modify the original DLL and don't want to create pinvode definitions? Create bridge classes in a new MCPP dll as demonstrated in approach B.
Conclusion
In this article I have presented the reader with a number of different approaches and solutions to the problem of programming aling an unmanaged C ++ class to C #. for the sake of bresponi have only supported DedCallPassInt()
Examples in this article, however...
Collapse
CallPassString()CallReturnString()
... Are in the source code accompanying this article.