Send C++ string to C# string. Interop

2019-03-17 01:57发布

问题:

I am new to inter process communication and need some help. I want to be able to send a string from a C++ program to a C# program. My problem is that the resultant string is gibberish. Here is my code:

Sending program (C++):

void transmitState(char* myStr)
{

    HWND hWnd = ::FindWindow(NULL, _T("myApp v.1.0"));
    if (hWnd)
    {
        COPYDATASTRUCT cds;
        ::ZeroMemory(&cds, sizeof(COPYDATASTRUCT));
        cds.dwData = 0;
        cds.lpData = (PVOID) myStr;
        cds.cbData = strlen(myStr) + 1;

        ::SendMessage(hWnd, WM_COPYDATA, NULL, (LPARAM)&cds);
    }
}   

And the receiving program (C#) (I have already overridden the WndProc):

private void OnCopyData(ref Message m)
{
    COPYDATASTRUCT cds = new COPYDATASTRUCT();
    cds = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));

    String myStr;
    unsafe
    {
        myStr = new String((char*) cds.lpData);
    }

    label1.Text = myStr;
}

回答1:

char* in C++ is ANSI character string (usually one byte per character), char* in C# is Unicode character string (like WCHAR* - two bytes per character).

You in fact reinterpret_cast from char* to WCHAR*. This won't work. Use MultiByteToWideChar() on C++ side to convert.



回答2:

Your string in C++ is ANSI. You need to convert to Unicode somewhere for C#. It's been a couple of years since I did interop, so someone else will have to tell you exactly how to do that.



回答3:

You'll have to convert your character array from ASCII to Unicode somehow. Here is a page that may help do it from the C# side.