Share via


Marshal.GetLastPInvokeError Méthode

Définition

Obtenez l’erreur d’appel de la dernière plateforme sur le thread actuel.

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

Retours

Dernière erreur d’appel de plateforme.

Exemples

L’exemple suivant définit un p/invoke avec DllImportAttribute.SetLastError défini sur true et illustre l’utilisation GetLastPInvokeError pour obtenir la dernière erreur 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}");
    }
}

Remarques

La dernière erreur d’appel de plateforme correspond au jeu d’erreurs par l’appel de plateforme le plus récent qui a été configuré avec DllImportAttribute.SetLastError défini sur true ou par un appel à SetLastPInvokeError(Int32), selon la dernière éventualité.

Cette méthode retourne uniquement les erreurs définies via les scénarios mentionnés. Pour obtenir la dernière erreur système indépendamment de l’utilisation de l’appel de plateforme, utilisez GetLastSystemError.

Cette méthode est fonctionnellement équivalente à GetLastWin32Error. Il est nommé pour mieux refléter l’intention de l’API et sa nature multiplateforme. GetLastPInvokeError doit être préféré à GetLastWin32Error.

S’applique à