提交C ++回调到.NET C ++ / CLI Wrapper

时间:2016-11-17 14:59:02

标签: c++ callback command-line-interface wrapper atl

我一直在网上搜索以下问题的解决方案,但无法理解它。

我们在C ++中有一个很棒的单片应用程序。要升级"在新的世界中,我们在其中嵌入了在C ++ / CLI托管包装器中生成的WPF视图。初始调用是通过智能指针从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

1 个答案:

答案 0 :(得分: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);
        }
    }