Search code examples
c#c++marshallingsendmessagewndproc

Cannot Marshal C++ char[] to C# string using Marshal.PtrToStringAuto(IntPtr)


I have been struggling with this problem for a few a while now and I one of my best friends (google) has yielded no help for me. Currently, I am working on a C# application (WinForms) that needs to take and use data from the LParam of a message sent by a C++ application. Currently, my C++ test application checks if a handle is available for the Message Receiver (C# application) and if the handle is valid, sends a message. The code for the C++ application is below:

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

I believe that the C++ application is working properly (builds and runs with no errors). I thought I would post it just to show how the message is being sent. A quick note is that the message number has no importance and I randomly chose it - Just in case if anyone was wondering.

My C# test application, which receives the message, is posted below:

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

When running these two applications at the same time, the C++ application successfully sends the C# application a message and the C# application processes the message until the stated point. The error message is:

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.

I have tried to also use Marshal.Copy with no luck. I have seen similar posts on StackOverflow about marshaling but I have not been able to resolve my issue with any solutions. Most other solutions detail how (which i believe that I am reproducing) but no other solutions detail this error that is being cause in this way.

Any help is greatly appreciated.


Solution

  • Two different applications have different address spaces, so the address in one application may be meaningless in another application. There are different ways to exchange info between processes. One of them is sending WM_COPYDATA. See for example here