无法使用 Marshal.PtrToStringAuto(IntPtr) 将 C++ char[] 封送到 C# 字符串

本文关键字:char 字符串 C++ Marshal PtrToStringAuto IntPtr | 更新日期: 2023-09-27 18:32:50

我已经为这个问题苦苦挣扎了一段时间,我最好的朋友之一(谷歌(没有为我提供任何帮助。目前,我正在开发一个 C# 应用程序 (WinForms(,该应用程序需要从 C++ 应用程序发送的消息的 LParam 中获取和使用数据。目前,我的 C++ 测试应用程序检查句柄是否可用于消息接收器(C# 应用程序(,如果句柄有效,则发送消息。C++应用程序的代码如下:

int _tmain(int argc, _TCHAR* argv[])
{
    HWND hScreenSaver = ::FindWindow(NULL,TEXT("MessageReceiver")); //MessageReceiveris the window name of the C# application
    if (hScreenSaver == NULL)
    {
        std::cout << "Handle Invalid!" << std::endl;
        return exit();
    }
    char testMessage[13] = "Test Message";
    ::SendMessageA(hScreenSaver, (UINT)101296, 0, (LPARAM)&testMessage);
    return exit();
}
int exit()
{
    system("Pause");
    return 0;
}

我相信C++应用程序工作正常(构建和运行没有错误(。我想我会发布它只是为了显示消息是如何发送的。快速说明是消息编号不重要,我随机选择了它 - 以防万一有人想知道。

收到消息的 C# 测试应用程序发布在下面:

protected override void WndProc(ref Message m)
{
    if(m.Msg == 101296)
    {
        if(m.LParam == IntPtr.Zero)
        {
            textBox1.Text = "Nothing Sent in LParam";
        }
        else
        {
            textBox1.Text = Marshal.PtrToStringAuto(m.LParam); //This is causing the error detailed below
        }              
    }
    base.WndProc(ref m);
}

同时运行这两个应用程序时,C++应用程序会成功向 C# 应用程序发送消息,C# 应用程序会处理该消息,直到达到规定的点。错误消息是:

A first chance exception of type 'System.AccessViolationException' occurred in mscorlib.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

我也尝试使用Marshal.Copy,但没有运气。我在 StackOverflow 上看到过关于封送处理的类似帖子,但我无法用任何解决方案解决我的问题。大多数其他解决方案详细说明了如何(我相信我正在重现(,但没有其他解决方案详细说明以这种方式引起的此错误。

任何帮助将不胜感激。

无法使用 Marshal.PtrToStringAuto(IntPtr) 将 C++ char[] 封送到 C# 字符串

两个不同的应用程序具有不同的地址空间,因此一个应用程序中的地址在另一个应用程序中可能毫无意义。在进程之间交换信息有不同的方法。其中之一是发送WM_COPYDATA。例如,请参阅此处