在带有WM_COPYDATA消息的结构中使用LPCTSTR是否安全?

我有这个结构:

typedef struct tagCOPY_PACKET
{
    TCHAR szFile[_MAX_PATH];
    GUID guidSignature;

} S_COPY_PACKET;

I prepare to send data with WM_COPYDATA like this:

CString strFile = GetFileToOpenFromFileExplorerPath();

S_COPY_PACKET sCopyDataPacket;
_tcscpy_s(sCopyDataPacket.szFile, _MAX_PATH, strFile);
sCopyDataPacket.guidSignature = CopyData_Signature;
COPYDATASTRUCT cds;
cds.dwData = COPYDATA_TYPE_MSA;
cds.cbData = sizeof(sCopyDataPacket);
cds.lpData = &sCopyDataPacket;

DWORD_PTR dwResult;
if (SendMessageTimeout(hOtherInstance, WM_COPYDATA,
                NULL, (LPARAM)(LPVOID)&cds, SMTO_BLOCK, 2000, &dwResult) != 0)
{
}

在另一端:

BOOL CMeetingScheduleAssistantDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
    if (pCopyDataStruct->dwData == COPYDATA_TYPE_MSA)
    {
        S_COPY_PACKET* pCopyPacket = (S_COPY_PACKET*)(pCopyDataStruct->lpData);
        if (pCopyPacket->guidSignature != CopyData_Signature)
        {
            // Bad GUID
            return FALSE;
        }

        if (GetLastActivePopup() != this) // Popup windows!
        {
            // TODO: Tell user?
            return FALSE;
        }

        theApp.SetFileToOpenFromFileExplorer(pCopyPacket->szFile);

        OpenFileFromFileExplorer();

        return TRUE;
    }

    return FALSE;
}

工作正常。我只是想知道更改这样的结构是否可以接受:

typedef struct tagCOPY_PACKET
{
    LPCTSTR lpszFile;
    GUID guidSignature;

} S_COPY_PACKET;

然后使用:

S_COPY_PACKET sCopyDataPacket;
sCopyDataPacket.lpszFile = strFile.GetBufferSetLength(_MAX_PATH);
sCopyDataPacket.guidSignature = CopyData_Signature;
COPYDATASTRUCT cds;
cds.dwData = COPYDATA_TYPE_MSA;
cds.cbData = sizeof(sCopyDataPacket);
cds.lpData = &sCopyDataPacket;

.... ....

并且,一旦消息已发布并处理:

strFile.ReleaseBuffer();

Is it safe to use the LPCTSTR approach with `WM_COPYDATA and if so, why?

评论
  • 一个人的伤悲
    一个人的伤悲 回复

    No. LPCTSTR is a pointer. So the recipient application will receive a pointer to a memory location of the sender application. It would cause the recipient application to crash due to a memory violation, had it tried to access the data.

  • cvitae
    cvitae 回复

    The documentation of WM_COPYDATA says:

    传递的数据不得包含指向接收数据的应用程序不可访问的对象的指针或其他引用。

    Therefore, when CMeetingScheduleAssistantDlg lives in a different executable, you cannot pass an LPCTSTR value. If it is in the same executable, chances are that it works.