Thursday, December 25, 2008

Interoperating with COM - Using COM from the .NET Framework (3)

How to Call Unmanaged DLLs Using DLLImport

Except adding a reference to unmanaged DLLs in Visual Studio, you also can import an unmanaged DLL programmatically.

Using (C#) or Imports (VB.NET) System.Runtime.InteropServices namespace and then use the DllImport attribute to import an unmanaged DLL.

Here is a sample in C# (from MSDN):
using System;
using System.Runtime.InteropServices;

class Example
{
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll")]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

static void Main()
{
// Call the MessageBox function using platform invoke.
MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
}
Also, you can use DLLImportAttribute's fields to have more control of the external functions. For example, if you want to call the MessageBox function using the new method name, you can specify the new function name using the EntryPoint property.

using System;
using System.Runtime.InteropServices;

class Example
{
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", EntryPoint = "TestMessageBox")]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

static void Main()
{
// Call the TestMessageBox function using platform invoke.
TestMessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
}
For more information about DLLImportAttribute members, please visit here: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute_members.aspx

No comments:

Post a Comment