c# System.ExecutionEngineError on P/Invoke 从大型数组调用

c# System.ExecutionEngineError on P/Invoke call from large arrays

我正在使用 P/Invoke 在 c# 中编写一个小型应用程序来创建 window。在处理大型数组时,PeekMessage 抛出了 System.ExecutionEngineException。这很奇怪,因为在实际使用数组时没有抛出异常并且一切都很好。但是当我调用 PeekMessage 时它抛出。不创建数组可以防止问题发生。发生异常时,将其打印到控制台:

Process terminated. A callback was made on a garbage collected delegate of type 'PInvoke.User32!PInvoke.User32+WndProc::Invoke'.
   at PInvoke.User32.PeekMessage(MSG*, IntPtr, WindowMessage, WindowMessage, PeekMessageRemoveFlags)
   at PInvoke.User32.PeekMessage(MSG*, IntPtr, WindowMessage, WindowMessage, PeekMessageRemoveFlags)
   at PInvoke.User32.PeekMessage(IntPtr, IntPtr, WindowMessage, WindowMessage, PeekMessageRemoveFlags)
   at Program.Main(System.String[])

我能够从我的项目中拼凑出下面的一个小样本,它重现了错误。我正在使用 .NET Core 3.1。

using System;
using System.Drawing;
using static PInvoke.Kernel32;
using static PInvoke.User32;

static class Program
{
    static IntPtr HWND;

    static unsafe void Main(string[] args)
    {
        // creating the arrays on lines 14, 16, and 26 somehow cause the error and creating the window after line 18 doesn't cause the error.

        HWND = CreateWindow();

        byte[] b = new byte[100000000];

        DoSomething(new int[10000]);

        PeekMessage(HWND, HWND, 0, 0, PeekMessageRemoveFlags.PM_REMOVE);
    }

    public static void DoSomething(int[] data)
    {
        Color[] result = new Color[data.Length];
    }

    static unsafe IntPtr WndProc(IntPtr hwnd, WindowMessage msg, void* wParam, void* lParam)
    {
        return DefWindowProc(hwnd, msg, (IntPtr)wParam, (IntPtr)lParam);
    }

    static unsafe IntPtr CreateWindow()
    {
        var hIsnt = GetModuleHandle(null);

        string classname = "test";
        WNDCLASS wndclass;

        fixed (char* pClassName = classname)
            wndclass = new WNDCLASS()
            {
                lpfnWndProc = WndProc,
                hInstance = hIsnt.DangerousGetHandle(),
                lpszClassName = pClassName
            };

        RegisterClass(ref wndclass);

        var hwnd = PInvoke.User32.CreateWindow(
            classname,
            "test",
            WindowStyles.WS_CAPTION |
            WindowStyles.WS_VISIBLE,
            100, 100, 1280, 720,
            IntPtr.Zero, IntPtr.Zero,
            hIsnt.DangerousGetHandle(),
            IntPtr.Zero
            );

        return hwnd;
    }

    static unsafe void HandleEvents()
    {
        MSG msg;
        while (PeekMessage(&msg, HWND, 0, 0, PeekMessageRemoveFlags.PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
}

如果您能提供任何帮助,我将不胜感激!

我明白了!问题是传递给非托管代码的 WndProc 委托被 GC 释放,使用大数组导致垃圾回收。简单的解决方法是保留 WndProc 委托传递给 window class.

的引用