Thursday, December 01, 2011

Managing the unmanaged... as in 5 tips toward understanding .Net Managed/Unmanaged Interop

simple-talk - 5 Tips for Understanding Managed-Unmanaged Interoperability in .NET

"Interop. The term alone can inspire fear, confusion, and uncertainty in many software developers. But there’s really nothing to fear from interoperability between managed and unmanaged code, especially if you learn a bit about what’s going on under the hood when you write interop code. Indeed, quite a few parts of the .NET Framework on Windows are implemented as platform invoke (P/Invoke) interop with native Windows DLLs. Windows Forms, for example, is primarily a P/Invoke-based wrapper around ComCtl32.dll. See: http://msdn.microsoft.com/en-us/magazine/dd315414.aspx.

P/Invoke is one of the two types of interop you will come across as a developer. You will most commonly use it to access C-style functions in Win32 DLLs, and C and C++ code in in-house and 3rd party libraries. Considering the magical things it does, it is often surprisingly easy to implement P/Invoke in order to call some specific bit of native functionality that your application needs.

The other type of interop is COM interop, which Visual Studio actually provides many tools to make easy. COM has a long history and there are many components out there that use it. This article is primarily about the memory aspects of interop so there are many aspects of COM interop that we’ll only briefly touch on and quite a few that we won’t see at all (e.g. differences in error handling mechanisms - see http://msdn.microsoft.com/en-us/library/9ztbc5s1.aspx). If you need to dive deep into COM interop, the MSDN documentation is one of the best sources of information there is: http://msdn.microsoft.com/en-us/library/bd9cdfyx.aspx. I also recommend searching around for materials about creating Microsoft Office add-ins using C# and VB since that’s a very rich source of COM interop information.

Interop code of either sort lets you access functionality in existing native and COM libraries that is not exposed by the .NET Framework. With it, you can take advantage of the speed and ease of .NET without needing to rewrite existing code that your projects depend on.

...

SNAGHTML210b5280

SNAGHTML210afd6e

image..."

A great document that provides some great information on Managed<>Unmanaged interop

 

Related Past Post XRef:
“I got your P/Invoke… right here…” But is it right?

.Net, Native, P/Invoke marshaling just like magic… “Marshaling with C# Pocket Reference” (Think “Marshalling Guide for the Busy Dev Guy”)
Signature/Data Type Conversion P/Invoke Cheat Sheet – aka What do you convert a wChar_t to .Net?
Marshall Fixed Length TCHAR Strings between Managed and Unmanaged Code

The PInvoke Interop Assistant Source is now on CodePlex
The PInvoke tool you've been looking for all this time... the "PInvoke Interop Assistant"

No comments: