我是进程间通信的新手,需要一些帮助。我希望能够将字符串从 C++ 程序发送到 C# 程序。我的问题是生成的字符串是乱码。这是我的代码:
发送程序(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);
}
}
以及接收程序(C#)(我已经覆盖了 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;
}