使用C ++将托管事件公开给COM

时间:2012-09-28 22:33:31

标签: c# c++ events com atl

可以公开用C#编写的托管事件,以便在使用c ++编写的COM对象中公开和使用。不熟悉com和atl。你能否说明一下MSDN文章

中显示的C ++方面会是什么样子

http://msdn.microsoft.com/en-us/library/dd8bf0x3.aspx

显示的VB6代码证明它是可行的。

3 个答案:

答案 0 :(得分:7)

在C ++中,最简单的方法是IMO在ATL的IDispEventImplIDispEventSimpleImpl模板的帮助下实现事件接收器。示例项目can be found here的解释。

有许多关于如何执行此操作的在线资源,例如: thisthis,但以下是所需步骤的列表:

首先让我们来看看管理方。

为了提供活动,我们必须执行以下操作:

  • 声明一个事件接口(IDispatch - 基于)
  • 使用ComSourceInterfaces属性标记coclass以将事件接口绑定到coclass
  • 在coclass中实现匹配事件

以下是托管代码:

[ComVisible(true), 
 Guid("D6D3565F-..."), 
 InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] //! must be IDispatch
public interface IMyEvents
{
    [DispId(1)] // the dispid is used to correctly map the events
    void SomethingHappened(DateTime timestamp, string message);
}

[ComVisible(true)]
[Guid("E22E64F7-...")]
[ProgId("...")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IMyEvents))] // binding the event interface
public class MyComServer : IMyComServer  
{
    // here we declare the delegate for the event
    [ComVisible(false)]
    public delegate void MyEventHandler(DateTime timestamp, string message);

    // and a public event which matches the method in IMyEvents
    // your code will raise this event when needed
    public event MyEventHandler SomethingHappened;
    ... 
}

现在,回到无人管理的一方。我将使用ATL,因为我发现它是编写COM客户端的最有效方法,但您可以尝试使用MFC或“手动”执行此操作。

需要执行以下步骤:

  • 接收器将继承IDispEventSimpleImpl(或IDispEventImpl
  • 声明所有需要的方法的接收地图
  • 为每个事件编写处理程序方法
  • 接收器已在事件源中注册
  • 最终,当不再需要时,水槽被断开

以下是ATL C ++客户端中的代码:

// import the typelib of your COM server
// 'named_guids' ensures friendly ID of event interface
#import "myserver.tlb" named_guids 
const UINT SINK_ID = 234231341; // we need some sink id

class MyClient : public IDispEventSimpleImpl<SINK_ID, MyClient, &MyServer::DIID_IMyEvents >
{
    public:
    // now you need to declare a sink map - a map of methods handling the events
    BEGIN_SINK_MAP(MyClient)
      SINK_ENTRY_INFO(SINK_ID, MyServer::DIID_IMyEvents, 0x1, OnSomethingHappened, &someEvent)
                                                   ^      ^      ^                   ^
      // event interface id (can be more than 1)---+      |      |                   |
      // must match dispid of your event -----------------+      |                   |
      // method which handles the event  ------------------------+                   |
      // type information for event, see below --------------------------------------+
    END_SINK_MAP()

// declare the type info object. You will need one for each method with different signature.
// it will be defined in the .cpp file, as it is a static member
static _ATL_FUNC_INFO someEvent;  // 'placeholder' object to carry event information (see below)

// method which handles the event
STDMETHOD (OnSomethingHappened)(DATE timestamp, BSTR message)
{ 
   // usually it is defined it in the .cpp file
}

... 

}

现在,我们需要在cpp文件中定义类型info成员(即上例中的someEvent实例):

_ATL_FUNC_INFO MyClient::traceEvent = { CC_STDCALL, VT_EMPTY, 2 , {VT_DECIMAL, VT_BSTR} };  // dispid = 1
                                               ^        ^     ^              ^
// calling convention (always stdcall) --------+        |     |              |
// type of return value (only VT_EMPTY makes sense) ----+     |              |
// number of parameters to the event -------------------------+              |
// Variant types of event arguments -----------------------------------------+

这可能很棘手,因为类型映射并不总是显而易见的(例如,托管int可能很清楚地映射到VT_I4,但DateTime映射到{VT_DECIMAL不太明显{1}})。 您需要声明计划在接收器地图中使用的每个事件 - 如果您不需要所有这些事件,请不要映射它们。

现在您需要将接收器连接到事件源:

// IUnknown* pUnk = interface to you COM server instance
pMyClient->DispEventAdvise(pUnk);
// .. from this point, events will be caught by the client
// when you are done, disconnect:
pMyClient->DispEventUnadvise(pUnk);

这就是它,或多或少。使用IDispEventImpl而不是IDispEventSimpleImpl会导致代码减少,因为您不需要提供可能是最丑陋部分的类型信息对象。但是,它有两个缺点:

  • 需要访问typelib(因为它需要读取接口元数据以便自己提供类型信息)
  • 有点慢(但我猜不会显着)

答案 1 :(得分:0)

如果你可以使用C ++ / CLI,你可以这样做(source):

// class that defines methods that will called when event occurs
ref class EventReceiver {
public:
   void OnMyClick(int i, double d) {
      Console::WriteLine("OnClick: {0}, {1}", i, d);
   }

   void OnMyDblClick(String^ str) {
      Console::WriteLine("OnDblClick: {0}", str);
   }
};

int main() {
   EventSource ^ MyEventSource = gcnew EventSource();
   EventReceiver^ MyEventReceiver = gcnew EventReceiver();

   // hook handler to event
   MyEventSource->OnClick += gcnew ClickEventHandler(MyEventReceiver, &EventReceiver::OnMyClick);
}

答案 2 :(得分:0)

Zdeslav Vojkovic提出的解决方案几乎是我的完整答案,但是在Outlook外接程序中实现接收器时遇到了稳定性问题。第一次取消建议后,系统变得不稳定,可能在下一个建议时崩溃。对我来说,解决方案是将接收器设为COM对象。

为简洁起见,我只添加了解决方案的ATL方面,因为托管代码可以完全按照Zdeslav Vojkovic的建议保留。

我在Visual Studio 2017中遵循了以下步骤:

创建ATL简单对象

  1. 右键单击项目,然后选择添加>新建项...
  2. 选择ATL简单对象,然后单击“添加”按钮
  3. 在“其他”标签中,为“线程模型”选择“单一”
  4. 单击完成

填写接收器界面详细信息

在生成的idl中添加用于初始化和关闭的处理程序:

[
    object,
    uuid(a5211fba-...),
    dual,
    nonextensible,
    pointer_default(unique)
]
interface IMyClient : IDispatch
{
    [id(1), helpstring("method InitHandler"), local] HRESULT InitHandler(IUnknown* myserver);
    [id(2), helpstring("method ShutdownHandler"), local] HRESULT ShutdownHandler(void); 
};

填写头文件(MyClient.h)

const UINT SINK_ID = 234231341;
extern _ATL_FUNC_INFO SomethingHappenedInfo;

// LIBID_MyATLComLib should point to the LIBID of the type library 
class ATL_NO_VTABLE CMyClient :
    public CComObjectRootEx<CComSingleThreadModel>,
    public CComCoClass<CMyClient, &CLSID_MyClient>,
    public IDispatchImpl<IMyClient, &IID_IMyClient, &LIBID_MyATLComLib, /*wMajor =*/ 1, /*wMinor =*/ 0>,
    public IDispEventSimpleImpl<SINK_ID, CMyClient, &MyServer::DIID_IMyEvents>
{
public:

    typedef IDispEventSimpleImpl</*nID =*/ SINK_ID, CMyClient, &MyServer::DIID_IMyEvents> SomethingHappenedEvent;

    ...

    BEGIN_SINK_MAP(CMyClient)
        SINK_ENTRY_INFO(SINK_ID, MyServer::DIID_IMyEvents, 0x1, OnSomethingHappened, &SomethingHappenedInfo)
    END_SINK_MAP()

    ...

private:
    CComQIPtr<MyServer::IMyComServer> mMyComServer; 

public:    
    STDMETHOD(InitHandler)(IUnknown* myserver);
    STDMETHOD(ShutdownHandler)(void);

    void __stdcall OnSomethingHappened(DateTime timestamp, string message);     
};

某些生成的代码已保留为“ ...”

填写C ++代码(MyClient.cpp)

_ATL_FUNC_INFO SomethingHappenedInfo = { CC_STDCALL, VT_EMPTY, 2 , {VT_DECIMAL, VT_BSTR} };


STDMETHODIMP CMyClient::InitHandler(IUnknown* myserver)
{
    this->mMyComServer = myserver;
    SomethingHappenedEvent::DispEventAdvise((IDispatch*)this->mMyComServer);

    return S_OK;
}


STDMETHODIMP CMyClient::ShutdownHandler(void)
{    
    SomethingHappenedEvent::DispEventUnadvise(this->mMyComServer);          

    return S_OK;
}

void __stdcall CMyClient::OnSomethingHappened(DateTime timestamp, string message)
{   
    ...
}

请注意,此处的“建议/不建议”呼叫的处理方式有所不同。