Reputation: 24067
I'm writing on C#.
I like using event
. It's very natural for my classes to just publish event and don't care who and how will they process. However as I will need to migrate my code to c++ should I still use event
? How easy would be to rewrite such code to c++? Probably it makes sense to use other technics that easier to rewrite to c++?
upd i've found similar question C#-like events in C++, Composition
Upvotes: 2
Views: 503
Reputation: 4693
What to use instead of c# event to have code easy to port to c++?
If you are sure what you think about is only related to event, then I think you don't need to make any change.
Just write a underlying class for event, that reaches your goal.
You might have various ways to do. The first step would be thinkg about CALLBACKs.
Here I provide some code for example, invoking c++ callbacks through P-invoke and wrap into delegates in c#.
Import the callback:
[DllImport("devlink.dll")]
static extern int DLRegisterType2CallDeltas(uint pbxh,DLCALLLOGEVENT cb);
Define the delegate:
public delegate void DLCALLLOGEVENT(uint pbxh, StringBuilder info);
Declare the event:
public event EventHandler<CallLogEventArgs> CallLogEvent;
Wrap the event to call:
DLRegisterType2CallDeltas(
pbxHandle,
(pbxh, info) => {
lock(thisLock)
if(
default(EventHandler<CallLogEventArgs>)!=CallLogEvent
&&
pbxHandle==pbxh
)
CallLogEvent(this, new CallLogEventArgs(info));
}
);
You'd need to do something reversed/inverted in c++. But first of all, implement a class for event or delegate would get you closer to done what you've asked.
Upvotes: 1
Reputation: 16894
Events in .net (C# included) are just an interpretation of the Observer design pattern; any C ++ implementation of this same pattern will have "similar" behavior.
Edit: some quickly googled-for links on topic:
Upvotes: 2
Reputation: 2454
If in doubt you could always fall right back to the Windows API. Check out events etc. http://msdn.microsoft.com/en-us/library/windows/desktop/ms686364(v=vs.85).aspx.
I haven't written c++ for several years but used these quite happily then. In the .net world there are wrappers in System.Threading, but under the hood they're the same thing.
Obviously I'm assuming here that your target is (and will remain) Windows. This is a bit of a sledgehammer approach but I think it would be foolproof.
Upvotes: 0
Reputation: 25927
You can quite easily implement events in C++11 with lambdas and std::function.
Upvotes: 0