Export (0) Print
Expand All

DllImportAttribute.PreserveSig Field

Indicates whether the signature is a direct translation of the unmanaged entry point.

[Visual Basic]
Public PreserveSig As Boolean
[C#]
public bool PreserveSig;
[C++]
public: bool PreserveSig;
[JScript]
public var PreserveSig : Boolean;

Remarks

Most methods called with platform invoke do not return HRESULTs, making the HRESULT/[out, retval] conversion pointless. This is why the default behavior preserves the signature exactly as defined. This field is true by default.

Occasionally, you do want to override the default behavior to convert the signature. For example, the definition of a method such as HRESULT

CoCreateInstance(...) should set this field to false. When set to false, a call that returns an HRESULT of S_OK is transformed such that the [out, retval] parameter is used as the function return value. The S_OK HRESULT is discarded. For HRESULTs other than S_OK, the runtime throws an exception and discards the [out, retval] parameter. Only methods that return an HRESULT can undergo a conversion.

This field is similar to the PreserveSigAttribute; however, in contrast to the PreserveSig field, the default value for the attribute is false.

Example

[Visual Basic, C#] In some cases, Visual Basic developers use the DllImportAttribute, instead of using the Declare statement, to define a DLL function in managed code. Setting the PreserveSig field is one of those cases.

[Visual Basic] 
Imports System.Runtime.InteropServices
Public Class Win32
    <DllImport ("user32.dll", PreserveSig := False)> _
    Public Shared Function MessageBoxA (ByVal hWnd As _
    Integer, ByVal txt As String, ByVal caption As String, _
    ByVal Typ As Integer) As Integer 
    End Function
End Class
      
[C#] 
using System.Runtime.InteropServices;
public class Win32 {
    [DllImport("user32.dll", PreserveSig=false)]
    public static extern int MessageBoxA(int hWnd, String text, String 
       caption, uint type);
}
      
[C++]
using namespace System::Runtime::InteropServices;
typedef void* HWND;
[DllImport("user32", PreserveSig=true)]
extern "C" int MessageBoxA(HWND hWnd,
                          String* pText,
                          String* pCaption,
                          unsigned int uType);
      

[C++, JScript] No example is available for C++ or JScript. To view a Visual Basic or C# example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

DllImportAttribute Class | DllImportAttribute Members | System.Runtime.InteropServices Namespace | PreserveSigAttribute

Show:
© 2014 Microsoft