Marshal.GetLastPInvokeError Metodo

Definizione

Ottenere l'ultimo errore di richiamare la piattaforma nel thread corrente.

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

Restituisce

L'ultimo errore di richiamare la piattaforma.

Esempio

Nell'esempio seguente viene definito un valore p/invoke con DllImportAttribute.SetLastError impostato su true e viene illustrato l'uso GetLastPInvokeError per ottenere l'ultimo errore p/invoke.

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}");
    }
}

Commenti

L'ultimo errore di richiamare la piattaforma corrisponde all'errore impostato dall'richiamare della piattaforma più recente configurata con DllImportAttribute.SetLastError impostato su o da una chiamata a trueSetLastPInvokeError(Int32), che è successo l'ultimo.

Questo metodo restituirà solo errori impostati tramite gli scenari menzionati. Per ottenere l'ultimo errore di sistema indipendente dall'utilizzo della piattaforma invoke, usare GetLastSystemError.

Questo metodo equivale in modo funzionale a GetLastWin32Error. È denominato per riflettere meglio la finalità dell'API e la sua natura multipiattaforma. GetLastPInvokeError deve essere preferito rispetto GetLastWin32Errora .

Si applica a