C#到C ++进程,WM_COPYDATA用字符串传递struct

时间:2012-10-05 10:05:04

标签: c# interop c++-cli marshalling wm-copydata

从c#程序我想使用带有SendMessage的WM_COPYDATA与传统的c ++ / cli MFC应用程序进行通信。

我想传递一个包含字符串对象的托管结构。

我可以找到c ++应用程序的句柄,以便与SendMessage一起使用。

我不知道的是如何在另一端编组和读取结构及其字符串。特别是因为它包含非blittables。

人们认为这是可行的吗? 我将继续努力,但会很高兴有人做过这样的事情,告诉我它是否会起作用。

这是一些演示代码,如果它是一个c ++ / cli程序,并不难让它工作。 但是,我希望它在.Net类库中,以便可以轻松地重复使用。

//Quick demonstation code only, not correctly styled
int WINAPI WinMain(HINSTANCE hInstance,
                 HINSTANCE hPrevInstance,
                 LPSTR lpCmdLine,
                 int nCmdShow)
{               
    struct MessageInfo
    {
        int     nVersion;
        char   szTest[ 10 ];        
    };

    MessageInfo sMessageInfo;

    sMessageInfo.nVersion = 100;
    strcpy( sMessageInfo.szTest, "TEST");   

    COPYDATASTRUCT CDS;

    CDS.dwData = 1; //just for test
    CDS.cbData = sizeof( sMessageInfo );
    CDS.lpData = &sMessageInfo;

    //find running processes and send them a message
    //can't just search for "MYAPP.exe" as will be called "MYAPP.exe *32" on a 64bit machine
    array<System::Diagnostics::Process^>^allProcesses = System::Diagnostics::Process::GetProcesses();

    for each (System::Diagnostics::Process^ targetProcess in allProcesses)
    {        
        if (targetProcess->ProcessName->StartsWith("MYAPP", System::StringComparison::OrdinalIgnoreCase))
        {
            HWND handle = static_cast<HWND>(targetProcess->MainWindowHandle.ToPointer());

            BOOL bReturnValue = SendMessage( handle, WM_COPYDATA, (WPARAM)0, (LPARAM)&CDS ) == TRUE;
        }
    }

    return 0;
}

2 个答案:

答案 0 :(得分:9)

我有它的工作。

一种简单的方法是将结构序列化为单个字符串并传输字符串。 swhistlesoft博客很有帮助http://www.swhistlesoft.com/blog/2011/11/19/1636-wm_copydata-with-net-and-c

这可能足以提供简单的消息传递。 如有必要,可以在另一端重构结构。

如果一个包含任意数量字符串的结构要按原样编组,那么它必须是一个固定的大小,这是我没有得到的主要内容。 在

MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 9)

基本上设置大小以匹配c ++大小,在我们的例子中是一个TCHAR szTest [9];

为了通过WM_COPYDATA将.Net结构从c#转移到c ++(/ cli),我必须按照以下步骤进行:

[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern bool SetForegroundWindow(IntPtr hWnd);

public static uint WM_COPYDATA = 74;

//from swhistlesoft
public static IntPtr IntPtrAlloc<T>(T param)
    { 
        IntPtr retval = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(param)); 
        System.Runtime.InteropServices.Marshal.StructureToPtr(param, retval, false); 
        return (retval); 
    }

//from swhistlesoft
    public static void IntPtrFree(IntPtr preAllocated) 
    { 
        if (IntPtr.Zero == preAllocated) throw (new Exception("Go Home")); 
        System.Runtime.InteropServices.Marshal.FreeHGlobal(preAllocated); 
        preAllocated = IntPtr.Zero; 
    }

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    struct COPYDATASTRUCT
    {
        public uint dwData;
        public int cbData;
        public IntPtr lpData;
    }

    /// <summary>
    /// Dot net version of AppInfo structure. Any changes to the structure needs reflecting here.
    /// struct must be a fixed size for marshalling to work, hence the SizeConst entries
    /// </summary>
    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1)]
    struct AppInfoDotNet
    {
        public int   nVersion;            

        [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 9)]
        public string test;
    };

发送字符串:

    COPYDATASTRUCT cd = new COPYDATASTRUCT();
    cd.dwData = 2;

    cd.cbData = parameters.Length + 1;
    cd.lpData = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(parameters);

    IntPtr cdBuffer = IntPtrAlloc(cd);

    messageReceived = ((int)SendMessage(targetProcess.MainWindowHandle, WM_COPYDATA, IntPtr.Zero, cdBuffer)) != 0;

要在c ++中接收字符串:

else if(pCDS->dwData == 2)
    {
        //copydata message
        CString csMessage = (LPCTSTR)pCDS->lpData;
        OutputDebugString("Copydata message received: " + csMessage);
    }

发送struct:

            AppInfoDotNet appInfo = new AppInfoDotNet();
            appInfo.test = "a test";

            COPYDATASTRUCT cds3;
            cds3.dwData = 1;
            cds3.cbData = System.Runtime.InteropServices.Marshal.SizeOf(appInfo);

            IntPtr structPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(System.Runtime.InteropServices.Marshal.SizeOf(appInfo));
            System.Runtime.InteropServices.Marshal.StructureToPtr(appInfo, structPtr, false);

            cds3.lpData = structPtr;

            IntPtr iPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(System.Runtime.InteropServices.Marshal.SizeOf(cds3));
            System.Runtime.InteropServices.Marshal.StructureToPtr(cds3, iPtr, false);

            messageReceived = ((int)SendMessage(targetProcess.MainWindowHandle, WM_COPYDATA, IntPtr.Zero, iPtr)) != 0;

            System.Runtime.InteropServices.Marshal.FreeCoTaskMem(iPtr);
            System.Runtime.InteropServices.Marshal.FreeCoTaskMem(structPtr);

在c ++中接收struct:

LRESULT CMainFrame::OnCopyData( WPARAM wParam, LPARAM lParam )
{
    LRESULT lResult = FALSE;

    COPYDATASTRUCT *pCDS = (COPYDATASTRUCT*)lParam;

    //Matching message type for struct
    if(pCDS->dwData == 1)
    {
        AppInfo *pAppInfo = (AppInfo*)pCDS->lpData
        lResult = true;
    }

请注意这是演示代码,需要在样式,异常处理等方面工作......

答案 1 :(得分:1)

来自文档:

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

因此您需要将字符串打包到COPYDATASTRUCT.lpData中。如果每个字符串都有最大长度,那么可以将其嵌入固定长度的结构中

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

如果你只有一个变长字符串,你可以把字符串放在最后并使用一个标题后跟字符串数据

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());

如果您有多个可变长度字符串,您仍然可以使用标头并为每个字符串分配更多空格加上一个双空终止符,或者将所有字符串序列化为一个XML字符串。