2016-11-17 58 views
0

我一直在尋找網絡解決以下問題的解決方案,但無法解決它。提交C++回調到.NET C++/CLI包裝器

我們在C++中有一個巨大的單片應用程序。爲了將其「升級」到新的世界,我們在WPF視圖中嵌入了一個C++/CLI託管包裝器中生成的視圖。最初的調用是通過智能指針從C++進行的。

 if (SUCCEEDED(ptr.CreateInstance(__uuidof(CloudServices)))) 
    { 
     CRect rect; 
     pWndContainer->GetWindowRect(rect); 

     ptr->InitializeControl((LONG)pWndContainer->GetSafeHwnd(), ID_AIS_BALANCEMATRIX, bstr.m_str, rect.Width(), rect.Height()); 
    } 

而且在包裝類接口聲明如下

interface ICloudServices : IDispatch{ 
[id(1)] HRESULT InitializeControl([in] LONG hWndParent, [in] LONG controlTypeId, [in] BSTR parameters, [in] LONG width, [in] LONG height); 

而且在包裝中實現這樣

STDMETHODIMP CCloudServices::InitializeControl(LONG hWndParent, LONG controlTypeId, BSTR parameters, LONG width, LONG height) { ... } 

問題: 一切工作正常和WPF視圖在C++應用程序中呈現。現在我們需要從.NET代碼發回信息給C++。

如何向包裝器提交非託管回調函數作爲InitializeControl的參數,以及如何使用/將其轉換爲相關的.net委託?

See desired solution schematic

+0

C++代碼實現了COM服務器。回調是*事件*,[添加連接點](https://msdn.microsoft.com/en-us/library/7bkz4x17.aspx)。 –

+0

感謝您的肯定正確的建議。我已經看到如何在託管端實現實現,但是如何在C++中使用此事件?你有一個與我提供的原理圖相對應的例子嗎? –

回答

0

我們似乎沒有找到工作解決這個問題,所以我們結束了與發送信息回用WM_DATACOMPY。不是最有效的方法,但它的工作原理。

public void SendCommand(Command command) 
    { 
     // Find the target window handle. 
     IntPtr hTargetWnd = NativeMethod.FindWindow("OurAppNameInCpp", null); 
     if (hTargetWnd == IntPtr.Zero) 
     { 
      throw new Exception("Sending '{0}'. Unable to find the \"OurAppNameInCpp\" window".Args(command.AsXmlMessage)); 
     } 

     // Prepare the COPYDATASTRUCT struct with the data to be sent. 
     MyStruct myStruct; 

     myStruct.Message = command.AsXmlMessage; 

     // Marshal the managed struct to a native block of memory. 
     int myStructSize = Marshal.SizeOf(myStruct); 
     IntPtr pMyStruct = Marshal.AllocHGlobal(myStructSize); 
     try 
     { 
      Marshal.StructureToPtr(myStruct, pMyStruct, true); 

      COPYDATASTRUCT cds = new COPYDATASTRUCT(); 
      cds.cbData = myStruct.Message.Length + 1; 
      cds.lpData = Marshal.StringToHGlobalAnsi(myStruct.Message); 

      // Send the COPYDATASTRUCT struct through the WM_COPYDATA message to 
      // the receiving window. (The application must use SendMessage, 
      // instead of PostMessage to send WM_COPYDATA because the receiving 
      // application must accept while it is guaranteed to be valid.) 
      NativeMethod.SendMessage(hTargetWnd, WM_COPYDATA, IntPtr.Zero, ref cds); 

      int result = Marshal.GetLastWin32Error(); 
      if (result != 0) 
       throw new Exception("SendMessage(WM_COPYDATA) failed w/err 0x{0:X}".Args(result)); 
     } 
     finally 
     { 
      Marshal.FreeHGlobal(pMyStruct); 
     } 
    }