c# programmer tries for events in c++ - c++

Hi all: I'm an experienced c# programmer trying to do some work in c++, and I'm not sure about the right way to do this:
I am authoring a class that needs to notify a consuming class that something has happened.
If I were writing this in c#, I would define an event on my class.
No events in c++, so I am trying to figure out what is the correct way to do this. I have thought about callback functions, but how do I handle a case where I want to execute a member function (not a static function).
More specifically, what I really need to do is to handle the event, but have access to member state within the object instance that is handling the event.
I have been looking at std::tr1:function, but I am having trouble getting it to work.
I don't suppose that anyone would want to translate the following example c# example into an example of the correct/best practice c++ (I need ANSI c++)?
(please bear in mind that I have almost no c++ experience -- don't assume that I know any long-established c++ conventions -- I don't ;);
A simple c# console app (works on my machine):
using System;
namespace ConsoleApplication1
{
public class EventSource
{
public event EventHandler<EchoEventArgs> EchoEvent;
public void RaiseEvent(int echoId)
{
var echoEvent = this.EchoEvent;
if (echoEvent != null)
echoEvent(this, new EchoEventArgs() {EchoId = echoId});
}
}
public class EchoEventArgs : EventArgs
{
public int EchoId { get; set; }
}
public class EventConsumer
{
public int Id { get; set; }
public EventConsumer(EventSource source)
{
source.EchoEvent += OnEcho;
}
private void OnEcho(object sender, EchoEventArgs args)
{
// handle the echo, and use this.Id to prove that the correct instance data is present.
Console.WriteLine("Echo! My Id: {0} Echo Id: {1}", this.Id, args.EchoId);
}
}
internal class Program
{
private static void Main(string[] args)
{
var source = new EventSource();
var consumer1 = new EventConsumer(source) { Id = 1 };
var consumer2 = new EventConsumer(source) { Id = 2 };
source.RaiseEvent(1);
Console.ReadLine();
}
}
}

The basic idea is to take function objects, e.g., something like std::function<Signature> as the callbacks. These aren't function pointers but can be called. The standard C++ library (for C++ 2011) contains a number of class and functions, e.g., std::mem_fn() and std::bind() which allow using functions, including member functions, to be used as function objects.
The part what is missing is something supporting multiple events be registered: std::function<Signature> represents one function. However, it is easy to put them, e.g., into a std::vector<std::function<Signature>>. What becomes more interesting (and requires variadic templates to be done easily) is creating an event class which encapsulates the abstraction of multiple events begin registered, potentially unregistered, and called.

C++ has a concept of functor: a callable object. You need to read about them.
Think about an object that has overwritten operator(). You pass an instance of such an object. After that you can call it like a regular function. And it can maintain a state.

There's also Signals2 library in Boost, which provides an API very close to real C# events, at least in idiomatic sense.

Qt has something that might help you called Signals and Slots: http://qt-project.org/doc/qt-4.8/signalsandslots.html
It lets you specify what the signals (the events that you want to listen to) and the slots (the receiving side) an object has, and then you can connect them. More than one object can listen to a signal like you mention you needed.
Qt is a large app framework, so I'm not sure how to use only the signals & slots part of it. But if you're building an entire GUI application the rest of the Qt might benefit you too (a lot of the ui event stuff is based on signals and slots).

Related

Override System class in Java and more precisely currentTimeMillis [duplicate]

Aside from recompiling rt.jar is there any way I can replace the currentTimeMillis() call with one of my own?
1# The right way to do it is use a Clock object and abstract time.
I know it but we'll be running code developed by an endless number of developers that have not implemented Clock or have made an implementation of their own.
2# Use a mock tool like JMockit to mock that class.
Even though that only works with Hotspot disabled -Xint and we have success using the code bellow it does not "persist" on external libraries. Meaning that you'd have to Mock it everywhere which, as the code is out of our control, is not feasible. All code under main() does return 0 milis (as from the example) but a new DateTime() will return the actual system millis.
#MockClass(realClass = System.class)
public class SystemMock extends MockUp<System> {
// returns 1970-01-01
#Mock public static long currentTimeMillis() { return 0; }
}
3# Re-declare System on start up by using -Xbootclasspath/p (edited)
While possible, and though you can create/alter methods, the one in question is declared as public static native long currentTimeMillis();. You cannot change it's declaration without digging into Sun's proprietary and native code which would make this an exercise of reverse engineering and hardly a stable approach.
All recent SUN JVM crash with the following error:
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00000, pid=4668, tid=5736
4# Use a custom ClassLoader (new test as suggested on the comments)
While trivial to replace the system CL using -Djava.system.class.loader JVM actually loads up the custom classLoader resorting to the default classLoader and System is not even pushed trough the custom CL.
public class SimpleClassLoader extends ClassLoader {
public SimpleClassLoader(ClassLoader classLoader) {
super(classLoader);
}
#Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return super.loadClass(name);
}
}
We can see that java.lang.System is loaded from rt.jar using java -verbose:class
Line 15: [Loaded java.lang.System from C:\jdk1.7.0_25\jre\lib\rt.jar]
I'm running out of options.
Is there some approach I'm missing?
You could use an AspectJ compiler/weaver to compile/weave the problematic user code, replacing the calls to java.lang.System.currentTimeMillis() with your own code. The following aspect will just do that:
public aspect CurrentTimeInMillisMethodCallChanger {
long around():
call(public static native long java.lang.System.currentTimeMillis())
&& within(user.code.base.pckg.*) {
return 0; //provide your own implementation returning a long
}
}
I'm not 100% sure if I oversee something here, but you can create your own System class like this:
public static class System {
static PrintStream err = System.err;
static InputStream in = System.in;
static PrintStream out = System.out;
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) {
System.arraycopy(src, srcPos, dest, destPos, length);
}
// ... and so on with all methods (currently 26) except `currentTimeMillis()`
static long currentTimeMillis() {
return 4711L; // Your application specific clock value
}
}
than import your own System class in every java file. Reorganize imports in Eclipse should do the trick.
And than all java files should use your applicatikon specific System class.
As I said, not a nice solution because you will need to maintain your System class whenever Java changes the original one. Also you must make sure, that always your class is used.
As discussed in the comments, it is possible that option #3 in the original question has actually worked, successfully replacing the default System class.
If that is true, then application code which calls currentTimeMillis() will be calling the replacement, as expected.
Perhaps unexpectedly, core classes like java.util.Timer would also get the replacement!
If all of the above are true, then the root cause of the crash could be the successful replacement of the System class.
To test, you could instead replace System with a copy that is functionally identical to the original to see if the crashes disappear.
Unfortunately, if this answer turns out to be correct, it would seem that we have a new question. :) It might go like this:
"How do you provide an altered System.currentTimeMillis() to application classes, but leave the default implementation in place for core classes?"
i've tried using javassist to remove the native currentTimeMills, add a pure java one and load it using bootclasspath/p, but i got the same exception access violation as you did. i believe that's probably because of the native method registerNatives that's called in the static block but it's really too much to disassemble the native library.
so, instead of changing the System.currentTimeMills, how about changing the user code? if the user code already compiled (you don't have source code), we can use tools like findbugs to identify the use of currentTimeMillis and reject the code (maybe we can even replace the call to currentTimeMills with your own implementation).

C++ Unreal Engine encapsulate delegates

I'm new to unreal engine and c++. I have a class in which I define a delegate with one parameter and a return type:
DECLARE_DELEGATE_RetVal_OneParam(bool, FInteractionValidatorDelegate, APlayerController*)
I've added a property containing this delegate:
FInteractionValidatorDelegate Validator;
And in another class I bind the delegate:
SomeComponent->Validator.BindUObject(this, &AInteractable::IsValid)
This all works fine but I don't want to expose the delegate publicly thus I want to encapsulate it by adding a BindValidator() method to my component. What is the best method of doing this ?
you could write a function like this :
void yourComponent::BindValidator(UObject * obj, void(*func)(bool))
{
Validator.BindUObject(obj, func);
}
but I recommend against doing this, first because passing functions' pointers will make errors coming from this hard to find (delegates are already enough obfuscation, with lots of macros and generated functions), also you will not be able to expose this to blueprints.
In UE4's way of doing things you could just pass a delegate as a FName
like so :
void yourComponent::BindValidator(UObject * obj, FName functionName)
{
Validator.BindUFunction(obj, functionName);
}
Here it's the UE4 doing the functions' declaration matching.
Hope this helps!

OOP for global system/task monitoring class

I'm trying to create a performance monitor of sorts to run on a Particle board (STM32 based). I'm used to programming in c so the OOP approach is a bit new but I think it would fit well here.
For the purpose of this question let's assume I have two types of monitors:
Frequency. The application can call a "tick" method of the monitor to calculate the time since it last ran and store it.
Period- call a "start" and "stop" method of the monitor to calculate how long a process takes to run and store it.
What I would like to do is to create instances of these monitors throughout my application and be able to report on the stats of all monitors of all types from the main module.
I've read about the singleton design pattern which seems like it might be what I need but I'm not sure and I'm also concerned about thread safety with that.
I'm thinking I will create a "StatMonitor" class and a derived class "FrequencyMonitor" and "PeriodMonitor". Monitor would be a singleton and everywhere I wanted to create a new monitor I would request an instance of "Monitor" and use that like so:
freqMonitor * task1FreqMonitor = StatMonitor::GetInstance()->Add_Freq_Monitor("Task1");
The StatMonitor would track all monitors I've added and when I wanted to print the stats I could just call the printAll method which would iterate it's array of monitors and request their results like so:
StatMonitor::GetInstance()->PrintAllStats();
Am I going down the right path?
Your path sounds good, except that FrequencyMonitor and PeriodMonitor should not derive from the class that "manages" all these monitors (let's call it MonitorPrinter).
MonitorPrinter should be a singleton and could look like this:
class MonitorPrinter
{
public:
static MonitorPrinter& getInstance()
{
static MonitorPrinter monitorPrinter;
return monitorPrinter;
}
void printAllStats()
{
for (const auto& [_, frequencyMonitor] : _frequencyMonitors)
frequencyMonitor.print();
for (const auto& [_, periodMonitor] : _periodMonitors)
periodMonitor.print();
}
FrequencyMonitor& getFrequencyMonitor(std::string name)
{ return _frequencyMonitors[name]; }
PeriodMonitor& getPeriodMonitor(std::string name)
{ return _periodMonitors[name]; }
private:
MonitorPrinter() = default;
std::map<std::string, FrequencyMonitor> _frequencyMonitors;
std::map<std::string, PeriodMonitor> _periodMonitors;
};
Demo
(The const auto& [_, frequencyMonitor] is a structured binding).
FrequencyMonitor and PeriodMonitor should not have anything to do with singletons, and from your description, they need not be part of a class hierarchy either (as they have different interfaces). If you want, you can prevent users (other than the MonitorPrinter) from instantiating these classes using other techniques, but I won't elaborate on that here.
In short, there is no need to use OOP here. Use a singleton to provide (and keep track of) the monitors, and implement the monitors to your liking. Be wary of thread safety if this is relevant (the above is not thread-safe!).

Should instance fields access be synchronized in a Tapestry page or component?

If a page or component class has one instance field which is a non-synchronized object, f.ex. an ArrayList, and the application has code that structurally modifies this field, should the access to this field be synchronized ?
F.ex.:
public class MyPageOrComponent
{
#Persist
private List<String> myList;
void setupRender()
{
if (this.myList == null)
{
this.myList = new ArrayList<>();
}
}
void afterRender(MarkupWriter writer)
{
// Should this be synchronized ?
if (someCondition)
{
this.myList.add(something);
}
else
{
this.myList.remove(something);
}
}
}
I'm asking because I seem to understand that Tapestry creates only one instance of a page or component class and it uses this instance for all the connected clients (but please correct me if this is not true).
In short the answer is no, you don't have to because Tapestry does this for you. Tapestry will transform your pages and classes for you at runtime in such a way that wherever you interact with your fields, they will not actually be working on the instance variable but on a managed variable that is thread safe. The full inner workings are beyond me, but a brief reference to the transformation can be found here.
One warning, don't instantiate your page/component variables at decleration. I have seen some strange behaviour around this. So don't do this:
private List<String> myList = new ArrayList<String>;
Tapestry uses some runtime byte code magic to transform your pages and components. Pages and components are singletons but the properties are transformed so that they are backed by a PerThreadValue. This means that each request gets it's own copy of the value so no synchronization is required.
As suggested by #joostschouten you should never initialize a mutable property in the field declaration. The strange behaviour he discusses is caused beacause this will be shared by all requests (since the initializer is only fired once for the page/component singleton). Mutable fields should instead be initialized in a render method (eg #SetupRender)

Should I write components in Delphi instead of C++ Builder? How do I add events to a component?

I use C++ Builder (XE2) and I would need to develop some VCL components that would also be used in Delphi. As I understand C++ Builder supports Delphi code and Delphi components but not the other way around? If so, it would be better to start writing it in Delphi so that I don't do a double job?
Second part of my question is more technical; I know how to add a property in a VCL component but don't know how to add events. Could someone give me an example please (no matter Delphi or C++ Builder).
Thanks.
As I understand C++ Builder supports Delphi code and Delphi components but not the other way around?
On source level - yes.
But if you choose to distribute your library sourceless - BPL+DCP+DCU - then it would not matter, except for maybe some small incompatibilities, like Delphi lacking [] operator and C++ lacking virtual overloaded constructors.
Turns out this estimation was wrong. Read Remy's comment below
Most close to you example ov events is the VCL itself, sources are usually shipped with Delphi. If you have Delphi Starter/Trial without VCL sources - then get any opensource VCL library or component. Such as JediVCL or basically almost ANY VCL component with sources. For example any "FWS" (Free with sources) component 99% uses events.
Most basic and widely used event notifications type - such as TButton.OnClick, TForm.OnCreate and a lot of - is TNotifyEvent
Open Delphi Help for that type. Scroll to "See also" and see two links there.
Procedural types are like int (*f)(void) in C.
Events creating manual
Such as:
(borrowed code from about.delphi.com)
type
TState = (stStarted, stStopped);
TStateChangeEvent = procedure
(Sender : TObject; State : TState) of object;
TThirdComponent = class(TSecondComponent) // or whatever
private
{ Private declarations }
FState : TState;
FOnStart,
FOnStop : TNotifyEvent;
FOnStateChange : TStateChangeEvent;
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Start; override;
procedure Stop; override;
property State : TState
read FState;
published
{ Published declarations }
property OnStart : TNotifyEvent
read FOnStart
write FOnStart;
property OnStateChange : TStateChangeEvent
read FOnStateChange
write FOnStateChange;
property OnStop : TNotifyEvent
read FOnStop
write FOnStop;
end
Then you can do
procedure TThirdComponent.Start;
begin
inherited;
FState := stStarted;
if Assigned(OnStart) then OnStart(Self);
if Assigned(OnStateChange) then
OnStateChange(Self, State);
end;