Click here to Skip to main content
Click here to Skip to main content

Using Platform Invoke

, 10 Sep 2003
Rate this:
Please Sign up or sign in to vote.
All about how to use PInvoke.

Introduction

In this article, I will summarize some of the points involved in the usage of 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 specify unsafe code, which VB cannot.

Using PInvoke in VB

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

  1. Using Declare statement
    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 a VB keyword, then it is needed.
  2. Using DllImport
     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 VB.NET compiler converts Declare to DllImport, but if you need to use any advance options as mentioned below, you have to go for DllImport.

When using DllImport, the function from the DLL is implemented as an 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 then 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. Defaults to True.
CallingConvention The calling convention of a DLL entry point. Defaults to stdcall.
CharSet Indicates how to marshal string data and which entry point to choose when both ANSI and Unicode versions are available. Defaults to Charset.Auto.
EntryPoint This specifies the name or ordinal value of the entry point to be used in the DLL. If not given, function name is used as entry point.
ExactSpelling It controls whether the interop marshaler will perform name mapping.
PreserveSig Specifies whether to preserve function signature while conversion.
SetLastError 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 function is not instance dependent, and extern because 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 unsafe flag is not used, it will result in compiler error.

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

public unsafe class myUnsafeClass
{
      //This class can freely use unsafe code.
}
public class myUnsafeClass
{
      //This class can NOT use unsafe code.
     public unsafe void myUnsafeMethod
     {
            // this method can use unsafe code 
      }
}
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 is sometimes used within unsafe blocks to allow allocating a block of memory on the stack rather than on the heap.

  • fixed & pinning

    GC moves objects in managed heap when it compacts memory during a collection.

    If we need to pass a pointer to 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# using the fixed keyword.

  • MarshalAs

    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 are passing a string to a COM method, the default conversion is a COM BSTR; when we are passing 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 data types. But some of the functions need structures to be passed, which we have to handle differently from simple data types.

  • 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 which can be used with the StructLayout attribute.

Callback functions and passing arrays as parameters involve 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

*As the string is an immutable class in .NET, they aren't suitable for use as output parameters. So a StringBuilder is used instead.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

NetPointerIN
Web Developer
United States United States
Dev

Comments and Discussions

 
GeneralI have a problem in calling unmanaged code , your help is much appreciatedd Pinmemberseohwee30-Sep-06 23:25 
QuestionProblem with defining method signatures Pinmembert4urean16-Apr-06 6:58 
Generalvb.net error pinvoke PinmemberAUTOCADZZ13-Jun-04 20:40 
hello
i take this code and i translate it to vb.net for Enumerating Local Network Resources via WNetEnumResource
but i have some pinvoke error on parameter or function
any one have idea?
 
my code:
Imports System
Imports System.Collections
Imports System.Runtime.InteropServices
Namespace ServerEnumerator
'/
'/ The ServerEnum class is used to enumerate servers on the
'/ network.
'/

'/
Public Enum RESOURCESCOPE
RESOURCE_CONNECTED = &H1
RESOURCE_GLOBALNET = &H2
RESOURCE_REMEMBERED = &H3
RESOURCE_RECENT = &H4
RESOURCE_CONTEXT = &H5
End Enum 'RESOURCE_SCOPE
Public Enum RESOURCETYPE
RESOURCETYPE_ANY = &H0
RESOURCETYPE_DISK = &H1
RESOURCETYPE_PRINT = &H2
RESOURCETYPE_RESERVED = &H8
End Enum 'RESOURCE_TYPE
Public Enum RESOURCEUSAGE
RESOURCEUSAGE_CONNECTABLE = &H1
RESOURCEUSAGE_CONTAINER = &H2
RESOURCEUSAGE_NOLOCALDEVICE = &H4
RESOURCEUSAGE_SIBLING = &H8
RESOURCEUSAGE_ATTACHED = &H10
RESOURCEUSAGE_ALL = RESOURCEUSAGE_CONNECTABLE Or RESOURCEUSAGE_CONTAINER Or RESOURCEUSAGE_ATTACHED
End Enum 'RESOURCE_USAGE
Public Enum RESOURCEDISPLAYTYPE
RESOURCEDISPLAYTYPE_GENERIC = &H0
RESOURCEDISPLAYTYPE_DOMAIN = &H1
RESOURCEDISPLAYTYPE_SERVER = &H2
RESOURCEDISPLAYTYPE_SHARE = &H3
RESOURCEDISPLAYTYPE_FILE = &H4
RESOURCEDISPLAYTYPE_GROUP = &H5
RESOURCEDISPLAYTYPE_NETWORK = &H6
RESOURCEDISPLAYTYPE_ROOT = &H7
RESOURCEDISPLAYTYPE_SHAREADMIN = &H8
RESOURCEDISPLAYTYPE_DIRECTORY = &H9
RESOURCEDISPLAYTYPE_TREE = &HA
RESOURCEDISPLAYTYPE_NDSCONTAINER = &HB
End Enum 'RESOURCE_DISPLAYTYPE
Public Class ServerEnum
Implements IEnumerable 'ToDo: Add Implements Clauses for implementation methods of these interface(s)
 
Enum ErrorCodes
NO_ERROR = 0
ERROR_NO_MORE_ITEMS = 259
End Enum 'ErrorCodes
_
Public Class NETRESOURCE
Public dwScope As RESOURCESCOPE = 0
Public dwType As RESOURCETYPE = 0
Public dwDisplayType As ResourceDisplayType = 0
Public dwUsage As RESOURCEUSAGE = 0
Public lpLocalName As String = Nothing
Public lpRemoteName As String = Nothing
Public lpComment As String = Nothing
Public lpProvider As String = Nothing
End Class 'NETRESOURCE
 
Private aData As New ArrayList
Public ReadOnly Property Count() As Integer
Get
Return aData.Count
End Get
End Property
_
Function WNetOpenEnum(ByVal dwScope As RESOURCESCOPE, ByVal dwType As RESOURCETYPE, ByVal dwUsage As RESOURCEUSAGE, ByVal p As NETRESOURCE, ByRef lphEnum As IntPtr) ' As NERR
End Function
 
_
Function WNetCloseEnum(ByVal hEnum As IntPtr) As ErrorCodes
End Function
 
_
Function WNetEnumResource(ByVal hEnum As IntPtr, ByRef lpcCount As Integer, ByVal buffer As IntPtr, ByRef lpBufferSize As Integer) As ErrorCodes
End Function
Private Sub EnumerateServers(ByRef pRsrc As NETRESOURCE, ByRef scope As RESOURCESCOPE, ByRef type As RESOURCETYPE, ByRef usage As RESOURCEUSAGE, ByRef displayType As ResourceDisplayType)
Dim bufferSize As Integer = 16384
Dim buffer As IntPtr = Marshal.AllocHGlobal(bufferSize)
Dim handle As New IntPtr(0) ' = IntPtr.Zero
Dim result As ErrorCodes
Dim cEntries As Integer = 1
 
'here the error
 
result = WNetOpenEnum(RESOURCESCOPE.RESOURCE_CONNECTED, RESOURCETYPE.RESOURCETYPE_ANY, Nothing, Nothing, handle)
 
If result = ErrorCodes.NO_ERROR Then
Do
result = WNetEnumResource(handle, cEntries, buffer, bufferSize)
 
If result = ErrorCodes.NO_ERROR Then
Marshal.PtrToStructure(buffer, pRsrc)
 

If pRsrc.dwDisplayType = displayType Then
aData.Add(pRsrc.lpLocalName)
aData.Add(pRsrc.lpRemoteName)
End If
 

If (pRsrc.dwUsage And RESOURCEUSAGE.RESOURCEUSAGE_CONTAINER) = RESOURCEUSAGE.RESOURCEUSAGE_CONTAINER Then
EnumerateServers(pRsrc, scope, type, usage, displayType)
End If
Else
If result <> ErrorCodes.ERROR_NO_MORE_ITEMS Then
Exit Do
End If
End If
Loop While result <> ErrorCodes.ERROR_NO_MORE_ITEMS
WNetCloseEnum(handle)
End If
 
Marshal.FreeHGlobal(CType(buffer, IntPtr))
End Sub 'EnumerateServers
Public Sub New(ByRef scope As RESOURCESCOPE, ByRef type As RESOURCETYPE, ByRef usage As RESOURCEUSAGE, ByVal displayType As ResourceDisplayType)
Dim pRsrc As New NETRESOURCE
 
EnumerateServers(pRsrc, scope, type, usage, displayType)
End Sub 'New
 
Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return aData.GetEnumerator()
End Function
End Class 'ServerEnum
End Namespace 'ServerEnumerator '
GeneralCorrection and More Info PinmemberBlake Coverett11-Sep-03 10:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 11 Sep 2003
Article Copyright 2003 by NetPointerIN
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid