How Do I...Call a Function Exported From an Unmanaged Library?
This example demonstrates how to call a function exported from an unmanaged library
from managed code. The MessageBox routine in User32.dll and GetSystemTime
routine in Kernel32.dll are called. The same technique can be used to call any exported
function in any other library.
In order to call MessageBox and GetSystemTime, you need the metadata that describes
each method and its arguments. The necessary metadata is provided by defining a managed class
with one or more static methods. The class and the static methods can have any name you choose.
You might want to create several classes that contain related functions or simply group all
the functions you need into a single class.
In C# the DllImport attribute is used to identify the name of the actual DLL that contains
the exported function. The method must be defined as static and external in order to apply
the attribute. In VB.NET the Declare statement serves the same purpose.
Many unmanaged DLL functions expect you to pass structures, as a parameter to the function.
When using platform invoke to pass a structure, you must provide additional
information to format the type. In managed code, a formatted type is a structure or class
that is annotated with the StructLayoutAttribute to ensure predictable layout
information to its members.
Once the class and methods are defined, the method can be called like any other method.
imports System.Runtime.InteropServices
Public Structure _
<StructLayout(LayoutKind.Sequential)> SystemTime
Public wYear As Short
...
End Structure
Public Class Win32
Declare Auto Sub GetSystemTime _
Lib "Kernel32.dll"(ByRef sysTime As SystemTime)
...
End Class
Public Class TestPInvoke
Public Shared Sub Main()
Dim sysTime As New SystemTime()
Win32.GetSystemTime(sysTime)
...
End Sub
End Class
VB
If the name of the method is different than the actual export name in the DLL,
the DllImport.EntryPoint property can be used to map the function to the correct
entry point if you are using C#. In Visual Basic you can use Alias keyword for this
purpose.
using System.Runtime.InteropServices;
Public Class Win32
...
Declare Auto Function MsgBox Lib "User32.dll" Alias "MessageBox" _
(hWnd As Integer, txt As String, caption As String, Typ As Integer) As Integer
End Class
Public Class TestPInvoke
Public Shared Sub Main()
...
Dim dt As String
dt = ...
Win32.MsgBox(0, dt, "Platform Invoke Sample", 0)
End Sub
End Class
VB
Also, you can specify the entry by ordinal rather than by name.
Declare Function MsgBox Lib "User32.dll" Alias "#452" _
(hWnd As Integer, txt As String, caption As String, Typ As Integer) As Integer
VB
PInvokeSimple.exe
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.
|