Marshal.GetLastPInvokeError 方法

定义

获取当前线程上最后一个平台调用错误。

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

返回

最后一个平台调用错误。

示例

以下示例定义设置为 true 的 p/invokeDllImportAttribute.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.SetLastErrortrue 的最新平台调用或由 调用 SetLastPInvokeError(Int32)的错误集,以上次发生的情况为准。

此方法仅返回通过上述方案设置的错误。 若要获取与平台调用用法无关的最后一个系统错误,请使用 GetLastSystemError

此方法在功能上等效于 GetLastWin32Error。 命名它的目的是更好地反映 API 的意图及其跨平台性质。 GetLastPInvokeError 应优先于 GetLastWin32Error

适用于