Interop with Native C++



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.



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

Invoke Native C++ DLL from .NET Code

Invoke .NET Assembly from Native C++ Code


Learning Links:

Interop (How Do I in Visual C++)

Best Practices For Managed And Native Code Interoperability

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

Managed/Native Code Interoperability