Muokkaa

Jaa


DllImportAttribute.SetLastError Field

Definition

Indicates whether the callee sets an error (SetLastError on Windows or errno on other platforms) before returning from the attributed method.

public: bool SetLastError;
public bool SetLastError;
val mutable SetLastError : bool
Public SetLastError As Boolean 

Field Value

Examples

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 SetLastError field is one of those cases.

[DllImport("user32.dll", SetLastError = true)]
int MessageBoxA(IntPtr hWnd, String^ Text,
    String^ Caption, unsigned int Type);
internal static class NativeMethods
{
    [DllImport("user32.dll", SetLastError = true)]
    internal static extern int MessageBoxA(
        IntPtr hWnd, string lpText, string lpCaption, uint uType);
}
Friend Class NativeMethods
    <DllImport("user32.dll", SetLastError:=True)>
    Friend Shared Function MessageBoxA(hWnd As IntPtr, lpText As String,
        lpCaption As String, uType As UInteger) As Integer
    End Function
End Class

Remarks

true to indicate that the callee will set an error via SetLastError on Windows or errno on other platforms; otherwise, false. The default is false.

If this field is set to true, the runtime marshaler calls GetLastError or errno and caches the value returned to prevent it from being overwritten by other API calls. You can retrieve the error code by calling GetLastPInvokeError on .NET 6.0 and above or GetLastWin32Error on .NET 5 and below or .NET Framework.

On .NET, the error information is cleared (set to 0) before invoking the callee when this field is set to true. On .NET Framework, the error information is not cleared. This means that error information returned by GetLastPInvokeError and GetLastWin32Error on .NET represents only the error information from the last p/invoke with DllImportAttribute.SetLastError set to true. On .NET Framework, the error information can persist from one p/invoke to the next.

Applies to

See also