tags:

views:

22

answers:

1

hi,

I need to send a VARIANT value to another application using COPYDATASTRUCT. Here is the structure i'm using to send messages.

struct {
   int     i_MsgId;
   VARIANT variant_Value;
}Message;

In my code I initialize the VARIANT to type BSTR and allocate a string as follows.

Message structMessage;
VariantInit(&structMessage.variant_Value);
structMessage.var_Value.vt = VT_BSTR;

structMessage.variant_Value.bstrVal = ::SysAllocString(L"I am a happy BSTR");

Then I send this using COPYDATASTRUCT as follows.

    COPYDATASTRUCT structCDS;

structCDS.cbData = sizeof(structMessage);
structCDS.dwData = 12;
structCDS.lpData = (LPVOID)(&structMessage);

::SendMessage(this->m_RemoteWindow,WM_COPYDATA,(WPARAM)this->GetSafeHwnd(),(LPARAM)&structCDS);

This message successfully receives to my second application, HOWEVER, when I cast it back to the original struct, "bstrVal" indicates a bad pointer.

I'm struggling with this error, so expecting your valuable help. Please note that other varinat types (int, double) can be successfully convert back, and this error ocus only with bstr. :(

Thank You

A: 

WM_COPYDATA will share your data structure (the one referenced by lpData) with the other application. Anything that is contained inside the data structure will be accessible by the other app. However, bstrVal is a pointer that references memory in your application, and when the other app tries to reference it, it is going to fail.

Here's one solution; it does require extra work on both the sides.

On the sender side, when you allocate your data structure (structMessage), add enough extra space to hold your string. Append the string to the end of the data structure (and be sure to increase dwData by the appropriate size).

On the receiver side, you can retrieve the string and use the SysAllocString call at that point to assign the bstrVal. Don't forget to call SysFree when you're done.

jdigital