问题描述
我有一个用 C# 编写的 COM 对象,我在 C++ 中使用它,并且在我不得不向它添加事件之前它没有问题。我曾尝试在此处查看无数教程、文档和问题,但奇怪的是,没有一个适合我的确切情况。
从我将事件源挂钩/取消挂钩到接收器的代码部分,我收到此错误:
Error C3731 incompatible event 'HRESULT eggplantClient::IeggplantClientEvents::Completed(void)' and handler 'HRESULT CReceiver::Completed(void)'; event source and event handler must have the same event type
我不知道这个“事件类型”是什么。我假设它是 CReceiver 类属性中的“com”部分:
[module(name = "EventReceiver")]
[event_receiver(com,true)]
class CReceiver {
...
至少这是我可以从 Microsoft documentation 中收集到的关于错误代码的信息。如果是这样,我如何将 C# 事件源设置为具有相同的类型?
Error C3702 ATL is required for COM events
这指向我定义 class CReceiver
的那一行。对于错误,我包含与 Microsoft documentation 中包含的头文件完全相同的头文件。我也从第 usage of ATL attributes is deprecated
行收到 [module(name = "EventReceiver")]
的警告,我认为这些是相关的?
我已经坚持了好几天了。这是我第一次用 COM 做事,即使是 COM 服务器的基本实现也很困难,但试图让事件工作一直是一场彻头彻尾的噩梦。如果有人能以任何方式对此提供帮助,我将非常感激,即使是一个教程的链接,该教程显示在 C++ 客户端中从 C# COM 服务器工作的事件也绰绰有余。以下是迄今为止我能够拼凑起来的相关部分。我使用 this 作为客户端代码,服务器部分我什至找不到了,因为我已经浏览了这么多页面。
C# COM 服务器,事件源
namespace eggplantClient
{
[InterfaceType(ComInterfaceType.InterfaceIsIdispatch)]
[Guid("C61C7C47-BB98-4DF3-BC61-7CA9430EDE7A")]
[ComVisible(true)]
public interface IeggplantClientEvents
{
[dispId(1)]
void Completed();
}
[Guid("0a805b99-756a-493c-96b7-063400f171ed")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IeggplantClientEvents))]
[ProgId("eggplantClient.CeggplantClient")]
public class CeggplantClient : IeggplantClient
{
[ComVisible(false)]public delegate void CompletedDelegate();
public event CompletedDelegate Completed;
...
C++ COM 客户端,事件接收器
#define _ATL_ATTRIBUTES 1
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <stdio.h>
int Flag = 0;
[module(name = "EventReceiver")]
[event_receiver(com,true)]
class CReceiver {
public:
HRESULT Completed() {
printf_s("Event received");
Flag = 1;
return S_OK;
}
void HookEvent(eggplantClient::IeggplantClient* pSource) {
__hook(&eggplantClient::IeggplantClientEvents::Completed,pSource,&CReceiver::Completed);
}
void UnhookEvent(eggplantClient::IeggplantClient* pSource) {
__unhook(&eggplantClient::IeggplantClientEvents::Completed,&CReceiver::Completed);
}
};
解决方法
Events in .NET are seen as Connection Point 在本机端。您可以按照此处的说明将它们与 ATL 一起使用 ATL Connection Points 和 Event Handling Principles
这里有一个简短的回顾。
这是您的 C# 类
namespace Eggplant
{
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("C61C7C47-BB98-4DF3-BC61-7CA9430EDE7A")]
[ComVisible(true)]
public interface IEggplantClientEvents
{
[DispId(1)]
void Completed(string text);
}
[Guid("0a805b99-756a-493c-96b7-063400f171ed")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IEggplantClientEvents))]
[ProgId("EggplantClient.CEggplantClient")]
public class CEggplantClient
{
[ComVisible(false)] public delegate void CompletedDelegate(string text);
public event CompletedDelegate Completed;
public CEggplantClient()
{
// wait 2 seconds and then call every second
Task.Delay(2000).ContinueWith(async t =>
{
do
{
Completed?.Invoke("Time is " + DateTime.Now);
await Task.Delay(1000);
}
while (true);
});
}
}
}
您可以像这样使用 .NET Framework 注册您的 C# 类(将创建一个 Eggplant.tlb
文件):
%windir%\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe Eggplant.dll /codebase /tlb
注意:对于 .NET Core 和 .NET 5,您必须构建自己的 .TLB,或者将 C# .NET Core 代码复制到 .NET Framework .dll 中并使用它...
这是您的 C/C++ 代码(省略前向引用):
#include <windows.h>
#include <stdio.h>
#include <atlbase.h>
#include <atlcom.h>
#import "D:\kilroy\was\here\Eggplant\bin\Debug\Eggplant.tlb" // import the tlb
using namespace Eggplant; // #import by default puts generated code in a specific namespace
int main()
{
CoInitialize(nullptr);
{
CComPtr<IUnknown> app;
if (SUCCEEDED(app.CoCreateInstance(__uuidof(CEggplantClient))))
{
// sink events
auto sink = new CEggplantClientEventsSink();
if (SUCCEEDED(sink->Connect(app)))
{
// this message box allows us to wait while events arrive
MessageBox(nullptr,L"Click to stop listening",L"Events",MB_OK);
}
}
}
CoUninitialize();
return 0;
}
// this is the event sink
class CEggplantClientEventsSink : public CDispInterfaceBase<IEggplantClientEvents>
{
public:
CEggplantClientEventsSink() { }
HRESULT Invoke(DISPID dispid,DISPPARAMS* pdispparams,VARIANT* pvarResult)
{
switch (dispid)
{
case 1: // the Completed DISPID value
wprintf(L"Completed called text:%s\n",pdispparams->rgvarg[0].bstrVal);
break;
}
return S_OK;
}
};
// this is a generic support class to hook IDispatch events
// adapted from here: https://devblogs.microsoft.com/oldnewthing/20130612-00/?p=4103
template<typename DispInterface>
class CDispInterfaceBase : public DispInterface
{
LONG m_cRef;
CComPtr<IConnectionPoint> m_spcp;
DWORD m_dwCookie;
public:
CDispInterfaceBase() : m_cRef(1),m_dwCookie(0) { }
// IUnknown
IFACEMETHODIMP QueryInterface(REFIID riid,void** ppv)
{
*ppv = nullptr;
HRESULT hr = E_NOINTERFACE;
if (riid == IID_IUnknown || riid == IID_IDispatch || riid == __uuidof(DispInterface))
{
*ppv = static_cast<DispInterface*>(static_cast<IDispatch*>(this));
AddRef();
hr = S_OK;
}
return hr;
}
IFACEMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&m_cRef); }
IFACEMETHODIMP_(ULONG) Release() { LONG cRef = InterlockedDecrement(&m_cRef); if (!cRef) delete this; return cRef; }
// IDispatch
IFACEMETHODIMP GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 0; return E_NOTIMPL; }
IFACEMETHODIMP GetTypeInfo(UINT iTInfo,LCID lcid,ITypeInfo** ppTInfo) { *ppTInfo = nullptr; return E_NOTIMPL; }
IFACEMETHODIMP GetIDsOfNames(REFIID,LPOLESTR* rgszNames,UINT cNames,DISPID* rgDispId) { return E_NOTIMPL; }
IFACEMETHODIMP Invoke(DISPID dispid,REFIID riid,WORD wFlags,VARIANT* pvarResult,EXCEPINFO* pexcepinfo,UINT* puArgErr)
{
if (pvarResult) VariantInit(pvarResult);
return Invoke(dispid,pdispparams,pvarResult);
}
virtual HRESULT Invoke(DISPID dispid,VARIANT* pvarResult) = 0;
public:
HRESULT Connect(IUnknown* punk)
{
CComPtr<IConnectionPointContainer> spcpc;
HRESULT hr = punk->QueryInterface(IID_PPV_ARGS(&spcpc));
if (SUCCEEDED(hr)) hr = spcpc->FindConnectionPoint(__uuidof(DispInterface),&m_spcp);
if (SUCCEEDED(hr)) hr = m_spcp->Advise(this,&m_dwCookie);
return hr;
}
void Disconnect()
{
if (m_dwCookie)
{
m_spcp->Unadvise(m_dwCookie);
m_spcp.Release();
m_dwCookie = 0;
}
}
};
这是结果: