Marshal.GetLastPInvokeError 메서드

정의

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

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

반환

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

예제

다음 예제에서는 로 설정된 true p/invoke를 DllImportAttribute.SetLastError 정의하고 를 사용하여 GetLastPInvokeError 마지막 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}");
    }
}

설명

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

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

이 메서드는 기능적으로 와 GetLastWin32Error동일합니다. API의 의도와 플랫폼 간 특성을 더 잘 반영하기 위해 이름이 지정됩니다. GetLastPInvokeError 은 에 비해 GetLastWin32Error선호되어야 합니다.

적용 대상