Marshal.GetLastPInvokeError 메서드

정의

현재 스레드에서 마지막 플랫폼 호출 오류를 가져옵니다.

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

반품

마지막 플랫폼 호출 오류입니다.

예제

다음 예제에서는 설정된 p/invoke를 true 정의하고 마지막 p/invoke DllImportAttribute.SetLastError 오류를 가져오는 데 사용하는 GetLastPInvokeError 방법을 보여 줍니다.

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

설명

마지막 플랫폼 호출 오류는 설정된 것으로 구성된 DllImportAttribute.SetLastError 가장 최근의 플랫폼 호출 또는 마지막으로 발생한 호출에 SetLastPInvokeError(Int32)의해 설정된 true 오류에 해당합니다.

이 메서드는 언급된 시나리오를 통해서만 설정된 오류를 반환합니다. 플랫폼 호출 사용과 관계없이 마지막 시스템 오류를 얻으려면 .를 사용합니다 GetLastSystemError.

이 메서드는 기능적으로 .에 해당합니다 GetLastWin32Error. API의 의도와 플랫폼 간 특성을 더 잘 반영하도록 명명되었습니다. GetLastPInvokeError를 더 선호해야 합니다.GetLastWin32Error

적용 대상