Platform Invoke

Environment: .NET, Win32 API

Introduction

In this article, I will summarize some of the points involved in using PInvoke.

PInvoke is the mechanism by which .NET languages can call unmanaged functions in DLLs. This is especially useful for calling Windows API functions that aren't encapsulated by the .NET Framework classes, as well as for other third-party functions provided in DLLs.

PInvoke differs its usage while used in Visual C# or managed C++ compared with VB because those languages can use pointers or, say, unsafe code which VB cannot.

Using PInvoke in VB

There are mainly two ways in VB that you can use PInvoke.

  1. Using a "Declare" Statement:
  2. Declare Auto Function MyMessageBox Lib "user32.dll"
    Alias "MessageBox" (ByVal hWnd as Integer, ByVal msg as String,
                        ByVal Caption as String,
                        ByVal Tpe as Integer) As Integer
    
    Sub Main()
    
      MyMessageBox(0, "Hello World !!!", "Project" Title", 0)
    
    End Sub
    

    Auto/Ansi/Unicode: Character encoding type. Use Auto and leave it up to the compiler to decide.

    Lib: Library Name. Must be in quotes.

    Name & Alias name for function: If the DLL function name is same name as the VB keyword, it is needed.

  3. Using DllImport:
  4. Imports System.Runtime.InteropServices
    
    <DllImport("User32.dll")> Public Shared Function
    MessageBox(ByVal hWnd As Integer, ByVal txt As String,
               ByVal caption As String,
               ByVal typ As Integer) As Integer
    
    End Function
    
      Sub Main()
        MessageBox(0, "Imported Hello World !!!",
                   "Project Title", 0)
      End Sub
    

The Declare statement has been provided for backward compatibility with VB 6.0. Actually, the VB.NET compiler converts "declare" to "DllImport", but if you need to use any advance option as mentioned below, you have to go for DllImport.

When using DllImport, the function from the DLL is implemented as sn empty function with the name, arguments, and return type. It has the DllImport attribute, which specifies the name of the DLL containing the function. The runtime will search for it, looking in the current directory, the Windows System32 directory, and then in the Path. (If Name is a keyword, use square braces.)

Following is the list of parameters used with DllImport:

Parameter Description
BestFitMapping Marshaler will find a best match for chars that can't be mapped between Ansi & Unicode when Enabled. Default to True.
CallingConvention The calling convention of a DLL entry point. Default to stdcall.
CharSet Indicates how to marshal string data and which entry point to choose when both ANSI and Unicode versions are available. Default to Charset.Auto.
EntryPoint Specifies the name or ordinal value of the entry point to be used in the DLL. If not given, the function name is used as the entry point.
ExactSpelling Controls whether the interop marshaler will perform name mapping.
PreserveSig Specifies whether to preserve the function signature while converting.
SetLastError Specifies whether the method will call Win32 SetLastError API or not. To retrieve the error, use Marshal.GetLastWin32Error.
ThrowOnUnmappableChar If false, unmappable characters are replaced by a question mark (?). If true, an exception is thrown when an unmappable character is encountered.

Using PInvoke in C#

Unlike VB, C# does not have the Declare keyword, so we need to use DllImport in C# and Managed C++.

[DllImport("user32.dll"]

  public static extern int MessageBoxA(
    int h, string m, string c, int type);

Here, the function is declared as static because the function is not instance dependent, and extern because the C# compiler should be notified not to expect implementation.

C# also provides a way to work with pointers. C# code that uses pointers is called unsafe code and requires the use of keywords: unsafe and fixed. If the /unsafe flag is not used, it will result in a compiler error.

Any operation in C# that involves pointers must take place in an unsafe context. We can use the unsafe keyword at the class, method, and block levels, as shown below.

  1. public unsafe class myUnsafeClass
    {
      //This class can use unsafe code freely.
    }
  2. public class myUnsafeClass
    {
      //This class can NOT use unsafe code.
      public unsafe void myUnsafeMethod
      {
        // this method can use unsafe code
      }
    }
  3. public class myUnsafeClass
    {
      //This class can NOT use unsafe code.
      public void myUnsafeMethod
      {
        // this method too can NOT use unsafe code
        unsafe
        {
          // Only this block can use unsafe code.
        }
      }
    }

stackalloc:

The stackalloc keyword sometimes is used within an unsafe block to allow to allocate a block of memory on the stack rather than on the heap.

fixed & pinning:

GC moves objects in a managed heap when it compacts memory during a collection. If we need to pass a pointer from a managed object to an unmanaged function, we need to ensure that the GC doesn't move the object while its address is being used through the pointer. This process of fixing an object in memory is called pinning, and it's accomplished in C# by using the fixed keyword.

MarshalAs:

The MarshalAs attribute can be used to specify how data should be marshaled between managed and unmanaged code when we need to override the defaults. When we pass a string to a COM method, the default conversion is a COM BSTR; when we pass a string to a non-COM method, the default conversion is C- LPSTR. But, if you want to pass a C-style, null-terminated string to a COM method, you will need to use MarshalAs to override the default conversion.

So far, we have seen simple datatypes. But some of the functions needed structures to be passed; we have to handle that differently than simple datatypes.

StructLayout:

We can define a managed type that is the equivalent of an unmanaged structure. The problem with marshaling such types is that the common language runtime controls the layout of managed classes and structures in memory. The StructLayout attribute allows a developer to control the layout of managed types. Possible values for the StructLayout are Auto, Explicit, and Sequential. Charset, Pack, and Size are the optional parameters that can be used with the StructLayout attribute.

Using Callback Functions and Passing arrays as a parameter involves some more complications and can be the subject for the next article.

Parameter Type Mapping

One of the severe problems with using Platform Invoke is deciding which .NET type to use when declaring the API function. The following table will summarize the .NET equivalents of the most commonly used Windows data types.

Windows Data Type .NET Data Type
BOOL, BOOLEAN Boolean or Int32
BSTR String
BYTE Byte
CHAR Char
DOUBLE Double
DWORD Int32 or UInt32
FLOAT Single
HANDLE (and all other handle types, such as HFONT and HMENU) IntPtr, UintPtr, or HandleRef
HRESULT Int32 or UInt32
INT Int32
LANGID Int16 or UInt16
LCID Int32 or UInt32
LONG Int32
LPARAM IntPtr, UintPtr, or Object
LPCSTR String
LPCTSTR String
LPCWSTR String
LPSTR String or StringBuilder*
LPTSTR String or StringBuilder
LPWSTR String or StringBuilder
LPVOID IntPtr, UintPtr, or Object
LRESULT IntPtr
SAFEARRAY .NET array type
SHORT Int16
TCHAR Char
UCHAR SByte
UINT Int32 or UInt32
ULONG Int32 or UInt32
VARIANT Object
VARIANT_BOOL Boolean
WCHAR Char
WORD Int16 or UInt16
WPARAM IntPtr, UintPtr, or Object

*Because the string is an Immutable class in .NET, it isn't suitable for use as an output parameter. So, a StringBuilder is used instead.



Comments

  • load a dll

    Posted by lordsid on 09/26/2006 09:41pm

    how to load in runtime a Dll and execute function of the dll please respond with samples so...

    Reply
  • Really helpful

    Posted by Legacy on 10/08/2003 12:00am

    Originally posted by: vijaya

    The article is good and has helped ma a lot.But it would have been still better if the article had covered "Using Callbacks".

    Reply
  • Good Article

    Posted by Legacy on 10/08/2003 12:00am

    Originally posted by: Nagaraju Rao

    This Article is having very Good information about working of Garbage collector how to call the functions of COm vs Non Com dll methods

    Reply
  • Good Attempt.

    Posted by Legacy on 09/23/2003 12:00am

    Originally posted by: Angel Komarov

    I could only ask the source code to be attached (especially c#), and add an interesting article regarding this matter:

    http://msdn.microsoft.com/msdnmag/issues/03/07/NET/

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds