Marshal.GetLastPInvokeError Método

Definición

Obtenga el último error de invocación de plataforma en el subproceso actual.

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

Devoluciones

El último error de invocación de plataforma.

Ejemplos

En el ejemplo siguiente se define una p/invoke con DllImportAttribute.SetLastError establecida true en y se muestra el uso GetLastPInvokeError de para obtener el último error 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}");
    }
}

Comentarios

El último error de invocación de plataforma corresponde al error establecido por la invocación de plataforma más reciente que se configuró con establecida true en DllImportAttribute.SetLastError o mediante una llamada a SetLastPInvokeError(Int32), lo que sucedió en último lugar.

Este método solo devolverá errores establecidos a través de los escenarios mencionados. Para obtener el último error del sistema independiente del uso de invocación de plataforma, use GetLastSystemError.

Este método es funcionalmente equivalente a GetLastWin32Error. Se llama para reflejar mejor la intención de la API y su naturaleza multiplataforma. GetLastPInvokeError debe ser preferible a GetLastWin32Error.

Se aplica a