C# to C++ process with WM_COPYDATA passing struct with strings

后端 未结 2 1498
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 03:48

From a c# program I want to use WM_COPYDATA with SendMessage to communicate with a legacy c++/cli MFC application.

I want to pass a managed struct containing string obje

2条回答
  •  既然无缘
    2021-02-08 04:27

    From the documentation:

    The data being passed must not contain pointers or other references to objects not accessible to the application receiving the data.

    So you need to pack your string into COPYDATASTRUCT.lpData. If you have a max length for each string then you can embed it in a fixed length structure

    typedef struct tagMYDATA
    {
       char  s1[80];
       char  s2[120];
    } MYDATA;
    

    If you have only one variable length string you can put the string at the end and use a header followed by string data

    typedef struct tagMYDATA
    {
       int value1;
       float value2;
       int stringLen;
    } MYDATAHEADER;
    
    MyCDS.cbData = sizeof(MYDATAHEADER)+(int)stringData.size();
    MyCDS.lpData = new BYTE[MyCDS.cbData];
    memcpy(MyCDS.lpData,&dataHeader,sizeof*(MYDATAHEADER);
    StringCbCopyA (
        ((BYTE*)MyCDS.lpData)+sizeof*(MYDATAHEADER)
        ,stringData.size()
        ,stringData.c_str());
    

    If you have multiple variable length strings you can still use a header and allocate more spaces for every strings plus a double null terminator, or serialize everything into one XML string.

提交回复
热议问题