Tuesday, July 24, 2012

DllImportAttribute Class in C#

Indicates that the attributed method is exposed by an unmanaged dynamic-link library (DLL) as a static entry point.


Namespace:  System.Runtime.InteropServices
Assembly:  mscorlib (in mscorlib.dll)

You can apply this attribute to methods.
The DllImportAttribute attribute provides the information needed to call a function exported from an unmanaged DLL. As a minimum requirement, you must supply the name of the DLL containing the entry point.
You apply this attribute directly to C# and C++ method definitions; however, the Visual Basic compiler emits this attribute when you use the Declare statement. For complex method definitions that include BestFitMappingCallingConventionExactSpellingPreserveSigSetLastError,(MSDN LINK) or ThrowOnUnmappableChar (MSDN LINK) fields, you apply this attribute directly to Visual Basic method definitions.
Note   JScript does not support this attribute. You can use C# or Visual Basic wrapper classes to access unmanaged API methods from JScript programs.
For additional information about using the platform invoke service to access functions in unmanaged DLLs, see Consuming Unmanaged DLL Functions.(MSDN LINK)

The following code example shows how to use the DllImportAttribute attribute to import the Win32 MessageBox function. The code example then calls the imported method.

using System;
using System.Runtime.InteropServices;

class Example
{
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
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);
}
}

No comments:

Post a Comment