Interop with Native C++


 

Introduction

While you can write applications entirely in either managed or native code, it is possible to mix managed and native projects in the same solution. So this article lists the methods about interop with native C++.

Invoke .NET Assembly from Native C++ Code

1. Hosting API. Native VC++ module calls CLR Hosting APIs to host CLR, load and call the .NET assembly.

2. COM interop . If the .NET assembly can be exposed as a COM component, native VC++ module can call into the .NET assembly through .NET .

3. Reverse PInvoke. The managed code call native passing a delegate the native code can call back.

4. IJW. If the module containing native VC++ code is allowed to enable CLR, the native VC++ code can call .NET assembly directly through the “It Just Works”, or “IJW”, mechanism.

 

Invoke Native C++ DLL from .NET code

1. IJW or It Just Works. This is one of the greatest features that .NET Framework has provided to developers. You just recompile the old code on the new .NET platform. No or little changes are necessary. Don't forget though; it works in the C++ language only.

2. COM. The COM model works on both the unmanaged and managed environments. It's straightforward to perform a COM Invoke on .NET. But, if your unmanaged classes are not COM-ready, you probably won't rewrite all the old code to support COM.

3. P/Invoke or Platform Invoke. This mechanism allows you to import a class as functions at the attribute level. Basically, you import class methods one by one as individual functions, as you do with Win32 APIs.

 

Samples:

Microsoft All-In-One Code Framework has working examples that demonstrate the methods.

Invoke Native C++ DLL from .NET Code

http://1code.codeplex.com/wikipage?title=Invoke%20Native%20C%2b%2b%20DLL%20from%20.NET&referringTitle=Documentation

Invoke .NET Assembly from Native C++ Code

http://1code.codeplex.com/wikipage?title=Invoke%20.NET%20Assembly%20from%20Native%20C%2b%2b&referringTitle=Documentation

 

Learning Links:

Interop (How Do I in Visual C++)

http://msdn.microsoft.com/en-us/library/ms177552%28VS.90%29.aspx

Best Practices For Managed And Native Code Interoperability

http://msdn.microsoft.com/en-us/magazine/dd315414.aspx

Using Unmanaged C++ Libraries (DLLs) in .NET Applications

http://www.codeproject.com/KB/mcpp/usingcppdll.aspx

Managed/Native Code Interoperability

http://msdn.microsoft.com/en-us/library/bb677136.aspx

Skip to main content