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.
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct SystemTime {
public ushort wYear;
...
}
public class Win32 {
[DllImport("Kernel32.dll")]
public static extern void GetSystemTime(ref SystemTime sysTime);
...
}
public class TestPInvoke {
public static void Main() {
SystemTime sysTime = new SystemTime();
Win32.GetSystemTime(ref sysTime);
...
}
}
C#
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 {
...
[DllImport("User32.dll", EntryPoint="MessageBox", CharSet=CharSet.Auto)]
public static extern int MsgBox(int hWnd, String text, String caption, uint type);
}
public class TestPInvoke {
public static void Main() {
...
String date = ...;
Win32.MsgBox(0, date, "PInvoke Sample", 0);
}
}
C#
Also, you can specify the entry by ordinal rather than by name.
[DllImport("User32.dll", EntryPoint="#452")]
public static extern int MsgBox(int hWnd, String text, String caption, uint type);
C#
PInvokeSimple.exe
[This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\Interop\PInvokeSimple\]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.
|