Predefined Interop Support Attributes

The FCL provides a set of attributes you can use to mark up your objects with information that is used by the CLR marshaling services to alter their default marshaling behavior.

This section describes the most common attributes you need when interoperating with native Win32 DLLs. These attributes all exist in the System.Runtime.InteropServices namespace.

The DllImport Attribute

[DllImport (dll-name
  [, EntryPoint=function-name]?
  [, CharSet=charset-enum]?
  [, SetLastError=true|false]?
  [, ExactSpelling=true|false]?
  [, PreserveSig=true|false]?
  [, CallingConvention=callconv-enum?)]
  (for methods)

The DllImport attribute annotates an external function that defines a DLL entry point. The parameters for this attribute are as follows:

dll-name

A string specifying the name of the DLL.

function-name

A string specifying the function name in the DLL. This is useful if you want the name of your C# function to be different from the name of the DLL function.

charset-enum

A CharSet enum, specifying how to marshal strings. The default value is CharSet.Auto, which converts strings to ANSI characters on Win98, and to Unicode characters on WinNT.

SetLastError

If true, preserves the Win32 error info. The default is false.

ExactSpelling

If true, the EntryPoint must exactly match the function. If false, name-matching heuristics are used. The default is false.

PreserveSig

If true, the method signature is preserved exactly as it was defined. If false, an HRESULT transformation ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.