WM_COPYDATA 进程间通信 传结构体失败... - C++ Builder / Windows SDK/API
a.exe代码:
typedef struct backupinfo
{
String sign;
String backuppath;
}BackupInfo;
void __fastcall TForm1::btn1Click(TObject *Sender)
{
HWND hWnd = FindWindow("TForm1","Form2");
if(hWnd)
{
BackupInfo *backup = new BackupInfo() ;
backup->sign = "access";
backup->backuppath = "ddd";
COPYDATASTRUCT cds;
cds.dwData = 0 ;
cds.cbData = sizeof(BackupInfo);
cds.lpData = (PVOID)backup;
SendMessage(hWnd,WM_COPYDATA,NULL,(LPARAM)&cds);
}
}
b.exe代码:
typedef struct backupinfo
{
String sign;
String backuppath;
}BackupInfo;
void __fastcall TForm1::WndProc(Messages::TMessage &Message)
{
switch (Message.Msg)
{
case WM_COPYDATA:
{
COPYDATASTRUCT *cds;
cds = (COPYDATASTRUCT*)Message.LParam;
BackupInfo * backup = (BackupInfo*)(cds->lpData);
String sign = backup->sign;
....
break;
}
}
TForm::WndProc(Message);
}
不知道为什么b.exe程序backup结构体接收的数据总是为空...
我a.exe明明给结构体赋值了的
请哪位大哥帮帮忙,我想了一上午都不知道怎么回事,怎么改正???
[解决办法]
typedef struct backupinfo
{
String sign;
String backuppath;
}BackupInfo;
改成
typedef struct backupinfo
{
char sign[100];
char backuppath[100]; //长度自定
}BackupInfo;
String是一个字符串类,它内部维护的字符串是一个指针,你这样传只相当于传了一个指针过去. 程序居然没跳出非法内存操作错误?
废话一下,进程间通信最好只使用C语言自带的原生类型(有个术语好像叫POD),那些类即使是同一代码,不同的进程可能也会表现得不一样(依赖于编译选项),更何况往往还不知道类内部的工作方式.