Sunday, October 22, 2006

Using unmanaged code

^ What is Interoperation for?
There might be many lines of legacy code left for companies. If they had to rewrite and retest thiese codes prior to launching any new application developed in .NET, they would have never made the switch. Using an "all or nothing" approach with migrating to .NET is simply too expensive and time consuming for many companies with investments in legacy code.
By taking advantage of Interoperation, they are able to migrate their existing applications little by little, in a manner that was virtually transparent to clients. Were it not for Interoperation, they would have never made the migration.


^ Prior to advent of the .NET Framework, the COM Framework was the primary framework for developers to interact with the Windows operating system.

d The mechanism that serves as proxy so that the .NET runtime can communicate with a COM component is known as a Runtime Callable Wrapper (RCW), which handles the majority of the work between .NET and COM for you, including marshaling data types, handling events, and handling interfaces.

d Unlike pure .NET components, COM components must be registered before they can be used.
d Every COM components must have an entry in the Windows registry.

d After importing it, using an object contained in a given COM library is virtually identical to using ne created purely in .NET.

d What is Platform Invoke? and when to use it?

d Use Platform Invoke through the System.Runtime.InteropServices namespace:


  1. Create a static/shared external method with the name of the function you want to call.
  2. Decorate it with the DllImport attribute specifying the library that it should call.
  3. Call the method from your code.

Imports System.Runtime.InteropServices
Public Class InterExample


Private Shared Function GetForeWindow() As IntPtr
End Function

Public Shared Sub GetScreenDemo()
Dim DemoHandle = GetForeWindow()
End Sub

End Class
d Encapsulating DLL Functions: Because Platform Invoke calls is not elegant, it's often beneficial to create a class that exposes them and wraps this functionality. After all, much of the .NET Framework is composed of precisely this methodology.
@ You need to call an unmanaged function from your managed code by using Platform Invoke services. What should you do?
Create a class to hold DLL functions and then create prototype methods by using managed code.