Edit

Share via


Marshal.GetLastPInvokeError Method

Definition

Get the last platform invoke error on the current thread.

public:
 static int GetLastPInvokeError();
public static int GetLastPInvokeError ();
static member GetLastPInvokeError : unit -> int
Public Shared Function GetLastPInvokeError () As Integer

Returns

The last platform invoke error.

Examples

The following example defines a p/invoke with DllImportAttribute.SetLastError set to true and demonstrates using GetLastPInvokeError to get the last p/invoke error.

using System;
using System.Runtime.InteropServices;

// These functions specify SetLastError=true to propagate the last error from the p/invoke
// such that it can be retrieved using Marshal.GetLastPInvokeError().
internal static class Kernel32
{
    [DllImport(nameof(Kernel32), ExactSpelling = true, SetLastError = true)]
    internal static extern bool SetCurrentDirectoryW([MarshalAs(UnmanagedType.LPWStr)] string path);
}

internal static class libc
{
    [DllImport(nameof(libc), SetLastError = true)]
    internal static extern int chdir([MarshalAs(UnmanagedType.LPUTF8Str)] string path);
}

class Program
{
    public static void Main(string[] args)
    {
        // Call p/invoke with valid arguments.
        CallPInvoke(AppContext.BaseDirectory);

        // Call p/invoke with invalid arguments.
        CallPInvoke(string.Empty);
    }

    private static void CallPInvoke(string path)
    {
        if (OperatingSystem.IsWindows())
        {
            Console.WriteLine($"Calling SetCurrentDirectoryW with path '{path}'");
            Kernel32.SetCurrentDirectoryW(path);
        }
        else
        {
            Console.WriteLine($"Calling chdir with path '{path}'");
            libc.chdir(path);
        }

        // Get the last p/invoke error and display it.
        int error = Marshal.GetLastPInvokeError();
        Console.WriteLine($"Last p/invoke error: {error}");
    }
}

Remarks

The last platform invoke error corresponds to the error set either by the most recent platform invoke that was configured with DllImportAttribute.SetLastError set to true or by a call to SetLastPInvokeError(Int32), whichever happened last.

This method will only return errors set via the mentioned scenarios. To get the last system error independent of platform invoke usage, use GetLastSystemError.

This method is functionally equivalent to GetLastWin32Error. It is named to better reflect the intent of the API and its cross-platform nature. GetLastPInvokeError should be preferred over GetLastWin32Error.

Applies to