问题描述
我是新来的进程间通信,需要一些帮助。我希望能够从C ++程序发送一个字符串到C#程序。我的问题是,得到的字符串是乱码。这里是我的代码:
发送程序(C ++):
无效transmitState(字符* myStr中)
{
HWND的hWnd = :: FindWindow函数(NULL,_T(对myApp V.1.0));
如果(HWND)
{
COPYDATASTRUCT光盘;
:: 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):
私人无效OnCopyData(参考消息M)
{
COPYDATASTRUCT CDS =新COPYDATASTRUCT();
CDS =(COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam的typeof(COPYDATASTRUCT));
字符串myStr的;
不安全
{
myStr中=新的String((字符*)cds.lpData);
}
label1.Text = myStr的;
}
在C ++中的char *是ANSI字符串(每个字符通常是一个字节),字符*在C#中的Unicode字符串(如WCHAR * - 每个字符两个字节)。
您从CHAR事实上的reinterpret_cast *到WCHAR *。这是行不通的。在C ++端使用的MultiByteToWideChar()来转换。
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;
}
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.
这篇关于发送C ++字符串到C#字符串。互操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!