Using Unmanaged Code with .NET Framework

We use Platform Invoke or P/Invoke when we want to call on unmanaged Windows API in case we don’t have a wrapper built into the .NET Framework. We manage P/Invoke via System.Runtime.InteropServices namespace. In order to use P/Invoke we use DllImport attribute

namespace MyProg
{
    class WindowExample
    {
        private const Int32 BufferSize = 256;
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll")]
        private static extern Int32 GetMyWindowText(IntPtr hWnd,
            StringBuilder textValue, Int32 counter);
        public static void GetScreenDemo()
        {
            StringBuilder MyDemoBuilder = new StringBuilder(BufferSize);
            IntPtr DemoHandle = GetForegroundWindow();
            if (GetMyWindowText(DemoHandle, MyDemoBuilder, BufferSize) > 0)
            {
                Console.WriteLine(MyDemoBuilder.ToString());
            }
        }
    }
}

We can wrap the above mentioned class like that

WindowExample.GetMyScreenDemo();

If we need to employ conversion mechanism, we need to use MarshalAs attribute. By doing this we expose IntelliSense support.

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace MyDemoProj
{
    class MarshalAsDemo
    {
        [MarshalAs(UnmanagedType.LPStr)]
        public String FName;
        public String LName;
        [MarshalAs(UnmanagedType.Bool)]
        public Boolean IsCurrentlyWorking;
    }
}

In order to better design our libraries we should employ standards such as MSDN using following tools: http://www.gotdotnet.com/team/fxcop/ and guidelines http://www.gotdotnet.com/team/libraries/.

Normally CLR takes care or arranging class’s members when we use type but we can overwrite this behavior by using System.Runtime.InteropServices.StructLayoutAttribute.

  If we want to set default positioning in a structure to be marshaled, you can use the Layout.Sequential attribute.

In order to set value for the positioning in a structure, we can use Layout.Explicit attribute.

Callback functions are important in .NET and .NET Framework provides better handling of callback functions with the help of Delegates versus Function Pointers as it is traditionally done.

Another challenge with unmanaged code is exception handling which is harder than for managed code. In order to trap errors we need to use Windows API.

There are several limitations with unmanaged code that we cannot overcome. Performance is not as good due to overhead associated with marshaling; its not type safe; code security and versioning are not availed with prior versions of programming paradigms.