Marshal.GetLastPInvokeError Metoda

Definicja

Pobierz błąd ostatniego wywołania platformy w bieżącym wątku.

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

Zwraca

Ostatni błąd wywołania platformy.

Przykłady

W poniższym przykładzie zdefiniowano metodę p/invoke z ustawioną wartością DllImportAttribute.SetLastErrortrue i pokazano użycie metody GetLastPInvokeError w celu pobrania ostatniego błędu 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}");
    }
}

Uwagi

Ostatni błąd wywołania platformy odpowiada ustawieniu błędu przez najnowsze wywołanie platformy, które zostało skonfigurowane z ustawioną wartością DllImportAttribute.SetLastErrortrue lub przez wywołanie metody SetLastPInvokeError(Int32), w zależności od tego, co miało miejsce ostatnio.

Ta metoda zwróci tylko błędy ustawione za pośrednictwem wymienionych scenariuszy. Aby uzyskać ostatni błąd systemu niezależnie od użycia wywołania platformy, użyj polecenia GetLastSystemError.

Ta metoda jest funkcjonalnie równoważna .GetLastWin32Error Nazwa jest nazwana w celu lepszego odzwierciedlenia intencji interfejsu API i jej wieloplatformowego charakteru. GetLastPInvokeError opcja powinna być preferowana przez GetLastWin32Errorwartość .

Dotyczy