C ++/CLI中的观察者模式,用于混合托管/非托管 [英] Observer pattern in c++/cli for mixed managed/unmanaged
问题描述
我有一个包含C#UI,C ++/CLI混合模式互操作包装程序和一些本机c ++项目的系统.
I have a system comprising a C# UI, a C++/CLI mixed mode interop wrapper, and some native c++ projects.
我需要做的是设置一个系统,以便本机c ++代码可以发送日志消息,而UI可以报告该消息.
What I need to do is set up a system such that the native c++ code can send a log message, and the UI can report it.
我使用此设置了本机IObservable 作为模板,但是C#代码不能成为观察者.我的想法是在C ++/CLI中设置另一个观察者模式,该模式观察本机观察者,然后让C#实现.我使用此作为模板,但我我正在努力将其转换为有效的C ++/CLI.
I set up a native IObservable using this as a template, but then the C# code can't be an observer. My thought was to set up another observer pattern in C++/CLI, which observes the native observer, and to let the C# implement that. I used this as a template but I'm struggling to convert this into valid C++/CLI.
ref class Observable
{
public:
Observable(void);
virtual ~Observable(void);
event System::EventHandler^ SomethingHappened;
void DoSomething() {
System::EventHandler^ handler = SomethingHappened;
//if (handler != nullptr)
//{
handler(this, System::EventArgs::Empty);
//}//null check not permitted in C++/CLI
};
给出错误:C3918:要求SomethingHappened成为数据成员. 这是MSDN页面-但我无法确定我在做什么错.
Gives the error: C3918: requires SomethingHappened to be a data member. This is the MSDN page - but I can't identify what I'm doing wrong.
有什么建议吗?
谢谢, 梅兰妮
推荐答案
您正在尝试使用C#语法.事件在C ++/CLI中的工作方式略有不同,它们具有 提高访问器,以及添加和删除访问器.换句话说,一种触发事件的方法.如果您不提供显式版本,则编译器会自动生成一个.这使得发起活动非常简单:
You are trying to use C# syntax. Events work a little differently in C++/CLI, they have a raise accessor in addition to the add and remove accessor. In other words, a method that fires the event. The compiler auto-generates one if you don't provide your explicit version it. That makes raising the event very simple:
void DoSomething() {
SomethingHappened(this, System::EventArgs::Empty);
}
这篇关于C ++/CLI中的观察者模式,用于混合托管/非托管的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!