This attribute (and, in C#, the keyword
"extern") specifies
that a method
definition is implemented externally (usually in a DLL). Apply this
attribute to a method that has been declared (but not defined) to
specify the DLL name and entry point in which the method can be
found.
The attribute can be customized in a number of different ways to help
control the binding against the external method. The
CallingConvention value dictates how the
parameters to the call (and return value coming back) should be sent
to the function. CallingConvention.StdCall (used
for calling into _stdcall-declared functions,
which is most of the Win32 API set) and
CallingConvention.Cdecl (used for calling
functions declared directly from C or C++) are the two most common
values. The CharSet value indicates which
character set parameters to the call are expected to be, either
two-byte Unicode or one-byte ANSI. EntryPoint
indicates the name of the exported function from the DLL to bind to
(normally this is guessed from the name of the .NET-declared method),
and ExactSpelling indicates whether the .NET
compiler should attempt to "best
match" a declared DllImport
method against a possible set of exported functions. The
PreserveSig value indicates how .NET should treat
[out]-declared and
[retval]-declared parameters. By default, the .NET
compilers ignore the HRESULT return value on IDL-declared methods and
use the [retval]-declared parameter as the return
value; setting PreserveSig to
true turns this off.
BestFitMapping is used to define whether the CLR
should try to "best fit" Unicode
characters to ANSI equivalents, and is turned on by default.
ThrowOnUnmappableChar indicates whether an
exception should be thrown when the interop marshaler attempts to
convert an unmappable character, and is turned off by default.
Finally, because many Win32 APIs use the
GetLastError API call to note the exact reason a
call fails, the SetLastError value indicates
whether the caller should use that API to discover the reason for
failures.
public sealed class DllImportAttribute : Attribute {
// Public Constructors
public DllImportAttribute(string dllName);
// Public Instance Fields
public bool BestFitMapping;
public CallingConvention CallingConvention;
public CharSet CharSet;
public string EntryPoint;
public bool ExactSpelling;
public bool PreserveSig;
public bool SetLastError;
public bool ThrowOnUnmappableChar;
// Public Instance Properties
public string Value{get; }
}