Name

DllImportAttribute

Synopsis

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 is 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 ...

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.