C++ Java Handler equivilent - c++

I'm coming from a Java/C# background and am new to C++. I am writing a library and am trying to accomplish the same functionality as a Handler does in Java. My scenario is as follows:
I am building a WinRT library that a user will put into his mobile/desktop app. At some point, after some network communication happens, a piece of data will come in that I want to pass along to the user. In Java, I declare a public static Handler (but do not initialize it) that the user can initialize. When the data comes in, I send a message through that Handler, and the end user's declaration within their app gets called, receiving the message and grabbing the data from it.
I can't seem to find a way to do the same in C++. I have looked at all kinds of posts/documentation on delegates/function pointers, utilizing the mighty Google with keywords like "callback", "handler", and "delegate". I think I have a half-formed understanding that it work differently in C++, but nothing is bearing fruit.
Could anyone kindly point me in the right direction?

Pretty much the same as you'd do it in Java. In your library, define a pure virtual class (more-or-less analogous with Java interface) of the handler.
class somethinghandler
{
public:
virtual void somethinghappened(<stuff that happened>) = 0;
}
And define and implement a class to watch for the event and call the function defined in the handler. This class contains a pointer, or list of pointers, objects installed by the client and methods to add and remove clients. If possible, don't use pointers at all let something do all of the containing. Life is cleaner that way. If you can't, guard the pointers with shared_ptr so that they cannot easily be destroyed before they are removed from the watcher.
class somethingwatcher
{
public:
bool addClient(std::shared_ptr<somethinghandler> clientToAdd);
bool removeClient(std::shared_ptr<somethinghandler> clientToRemove);
void applogic();
private:
std::shared_ptr<somethinghandler> client;
// or std::vector<std::shared_ptr<somethinghandler>> clients;
}
Finally, somewhere in somethingwatcher's application logic you detect something happened and call the client.
void somethingwatcher::applogic()
{
// do stuff
if(<something happened>)
{
// or iterate through the list of clients and doing for each:
if (client != nullptr)
{
client->somethinghappened(<stuff that happened>);
}
}
}
The library doesn't need to know anything about the client other than it exists and implements the somethinghappened function defined in somethinghandler. So long as you have a valid pointer, magic happens. Well, not really but this isn't the right place to go into how that "magic" works.
Outside the library in Client Land...
The client code defines and implements a class that implements somethinghandler to receive calls to somethinghappened.
class somethingclient: public somethinghandler
{
public:
void somethinghappened(<stuff that happened>);
\\ handles something happening.
}
Assuming the client code has instantiated a somethingwatcher named watcher, then an initialization routine creates and adds a somethingclient to watcher.
std::shared_ptr<somethinghandler> handler = std::make_shared<somethingclient>(constructor arguments);
watcher.addClient(handler);

Related

Implementing a pure virtual function Change parameter from void* to specific type pointer

I have a base Class that implements all the mundane stuff with creating a server which spawns a thread, listens on a queue and processes the received messages.
Those messages are then given to a pure virtual function:
void ProcMsg(void* msg) = 0;
In the implementation of the derived Class when implementing the ProcMsg I would like to change the void* msg to a pointer to as specific message structure definition MyMsgType* msg. Is there a language construct that would allow me to do that or is the only way to re-cast the void* to MyMsgType* inside of the ProcMsg implementation.
The only thing I found is Templates, but I was hoping there would be a simpler way.
If you're using void * for any other reason beyond interfacing with some ancient C library, you probably want to rethink your architecture.
I would create a base class for all the messages that be passed and then have a virtual method on those called process or something like that. If that turns things around too much, then you might have to have a messageType field and query it, then do some typecasting.

GetFunctionPointerForDelegate callback only works once

I'm having trouble with unmanaged-to-managed callback in C++/CLI. It works exactly one time and then silently fails
My managed Device class holds an unmanaged object (GsDevice) from a separate DLL. It gives the unamanaged object a callback function set up via interop. GsDevice needs to asynchronously notify Device when things change.
The callback was silently failing every time. The debugger was stepping right over it (even in dissasembly. Then I tried to make GsDevice invoke the callback it as the moment it received it. THEN it works. Just the one time.
I assume something is being moved or garbage-collected out from under me but I cannot determine what or why. Can anyone spot what I am doing wrong?
Below is the unmanaged GsDevice class. It lives in a separate, unmanaged DLL. I've left out most of it except for the subscription mechanism that the managed client uses and the notify mechanism by which the this class calls back to the managed one.
The .H file
struct GsDeviceMembers;
class GsDevice : public std::enable_shared_from_this<GsDevice>
{
GsDeviceMembers* m_p; // PIMPL idiom
public:
typedef void (__stdcall *PROPCHANGECALLBACK)(GsDevice*, const std::string&);
void GsDeviceDllExport setPropertyChangedCallback(PROPCHANGECALLBACK cb);
protected:
void raisePropertyChanged(const std::string& prop);
}
And the .CPP file
void GsDevice::setPropertyChangedCallback(PROPCHANGECALLBACK cb)
{
std::unique_lock<std::mutex> lk (m_d->mtxClients);
cb(this, std::string("joe")); // TEST: Call callback right away to ensure it's good.
m_p->cb = cb; // Save off the one client's callback
}
void GsDevice::raisePropertyChanged(const std::string& prop)
{
std::unique_lock<std::mutex> lk (m_d->mtxClients);
m_p->cb(this, prop); // Invoke callback: THIS NEVER WORKS*****
}
Below is the managed client Device class that tries to receive callbacks from the unmanaged GsDevice.
The .H file
struct DeviceUnmanagedMembers; for PIMPL idiom storing unmanaged members.
public ref class Device : public INotifyPropertyChanged
{
public:
virtual event PropertyChangedEventHandler^ PropertyChanged;
private:
DeviceUnmanagedMembers* m_p; // PIMPL idiom
GCHandle m_callbackHandle; // Keeps callback locked into one memory address
protected:
Device(std::shared_ptr<GsDevice> dev);
delegate void PropertyChangedDelegate(GsDevice* sender, const std::string& propName);
virtual void OnPropertyChanged(Gs:Device* pSender, const std::string& propName);
private:
// I am saving off these as member variables in case it helps .NET keep things
// alive. So far, that's not working.
PropertyChangedDelegate^ m_dg;
System::IntPtr^ m_ptr;
};
The .CPP file
struct DeviceUnmanagedMembers
{
std::shared_ptr<GsDevice> spDevice;
DeviceUnmanagedMembers(std::shared_ptr<GsDevice> dev) : spDevice(dev) { }
};
Device::Device(std::shared_ptr<GsDevice> dev) : m_p(new DeviceUnmanagedMembers(dev))
{
// Get a delegate for our callback function and lock it into memory
auto pcDelegate = gcnew PropertyChangedDelegate(this, &Device::OnPropertyChanged);
m_callbackHandle = GCHandle::Alloc(pcDelegate);
auto callback = Marshal::GetFunctionPointerForDelegate(pcDelegate);
auto ptrInt = callback.ToPointer();
auto ptrFun = static_cast<GsDevice::PROPCHANGECALLBACK>(ptrInt);
// Now hook up to the unamanged client for a callback. This actually immediately
// calls me back (to OnPropertyChanged) but all subsequent attempts by the
// unmanaged object to call me back do nothing.
dev->setPropertyChangedCallback(ptrFun);
// Save off these items just in case it helps (It doesn't)
m_dg = pcDelegate;
m_ptr = callback;
}
void Device::OnPropertyChanged(GsDevice* sender, const std::string& propName)
{
// This is the function the unmanaged client is trying to call back. It works
// the very first time the client does it but never after.
RaisePropertyChanged(propName);
}
Notes:
Neither Device nor GsDevice object is being cleaned up. They both still exist because I continue to invoke them with function calls from managed to unmanaged code.
The unmanaged device keeps trying and failing to call the callback. No error. No exception. It just steps over the call.
I've compared the exact pointer values of the callback from the first time (when it works) and all subsequent times when it fails. Its exactly the same.
The C++/CLI assembly is built with .NET 5.0 and Visual Studio 2019
The unmanaged C++ code is built with C++17 features enabled (if that matters)
You appear to be doing the right things to prevent the garbage collector from tossing out the unmanaged trampoline generated by GetFunctionPointerForDelegate. (In Fact, either one of GCHandle.Alloc or keeping a member variable pointing to the delegate instance should be sufficient, you gain no benefit from doing both). This is a common trap for use of GetFunctionPointerForDelegate but it is not your problem.
The other thing I noticed is that you haven't made your delegate suitable for use with GetFunctionPointerForDelegate. Really, .NET just ought to throw an exception if you use GetFunctionPointerForDelegate on a delegate type that doesn't have the UnmanagedFunctionPointerAttribute applied to it.
Add that attribute to delegate void PropertyChangedDelegate(GsDevice* sender, const std::string& propName);, set the correct calling convention (and maybe other things), and try again.
Beyond that, your function type really is not .NET-friendly at all. GetFunctionPointerForDelegate does not expect to work with types like const std::string&.
Does the unmanaged API not provide some user context pointer where you can store a GCHandle to your managed object? If it does, then make an ordinary non-member function to pass as the callback (which you can now create with just &name_of_function -- no delegate, no GetFunctionPointerForDelegate) and in that function, retrieve the pointer, re-hydrate the GCHandle, find your managed object, convert the other argument to a System::String^ and call the .NET member function.
I am posting my own answer because while Ben's suggestions were excellent, the cause appears to have been something different: My liberal use of header-only, unmanaged classes in C++/CLI managed code. I've slowly come to realize that C++/CLI assemblies can become confused by this.
I unexpectedly saw my problems fixed merely by moving unmanaged code from header files to their own .CPP files (with attendant #pragma unmanaged statements for good measure). I was able to leave all my Interop code just as it was. No gcroots or data-type changes needed.
My best guess is that header-only code causes the compiler to fail to generate all of the necessary unmanaged-to-managed transitions in some places and that without such transitions, callbacks just don't work.
This was all complicated by having the added effect of making the debugger simply ignore breakpoints even when the code executed -- but only sometimes. I would repeatedly see a breakpoint on a log statement get hit far fewer times than the statement itself dumped. Again, all this seems to have been fixed merely by separating .CPP and .H unmanaged code.

Data Driven Design in native C++

So I am writing a game engine that utilizes data driven design to instantiate various actors from xml files. I recently finished coding the event management system and everything fires off the events and the handlers catch them correctly. No easy task considering I used member function pointers and templates. The issue I am having now is that I would like to be able to do something like this in the xml file:
<InputComponent>
<Event EventName="GainedFocus" OnEvent="Initialize"/>
</InputComponent>
The problem should be pretty obvious. C++ has no form of reflection and therefore cannot, as far as I know, get the address for the Initialize function from the string "Initialize". This means that for slightly different input components I have derive from the class and register the events specific to that instance and add the functions. Also, it should be known that this is different than the way I am handling typical input:
<InputComponent>
<Mapping Type="MousePress" Button=1 Command="RotateCamera"/>
</InputComponent>
In this instance mapping is an element specific to input components and commands are themselves objects that are created with a factory. I cannot really do this with generic events though. Commands are specific items that perform the exact same operations on different objects whereas objects or components themselves often need to handle individual events differently. Has anyone done anything like this before? Genuinely curious as to how someone could go about doing something like this so that events that need to be registered to an object dont have to be hard coded into the class itself.
EDIT: Let me word it this way. Different INSTANCES of the same type of components need to react differently to events. This will be application specific and as such should be separate from the engine code (I shouldn't have to modify the components). The user should be able to supply functions that can then be called upon reaction to an event. Both the function and event should be able to be bound in XML. I am starting to think this might just be impossible in unmanaged C++ because there is no form of metadata to look up the functions supplied by the user based on a string of the same name.
You could use a map that associates strings with function pointers.
Or if the function signatures differ you can use a Factory pattern with an if-else-if ladder.
Edit 1: Example
// Typedef for event functions
typedef void (*Event_Function_Pointer)(const Event& e);
typedef std::map<std::string, Event_Function_Pointer> Event_Function_Container;
//...
Event_Function_Container events;
events["Gained Focus"] = Initialize;
There's also an option of having lookup table since the text and the function pointers are constant data:
struct Event_Function_Entry
{
char * const * event_name;
Event_Function_Pointer event_function;
};
Event_Function_Entry events[] =
{
{"Gained Focus", Initialize},
};
Your components could all inherit from a same base, that provindes the interface for basic operations that your commands will invoque:
class Component {
public:
virtual void initialize();
virtual void rotate(int x, int y);
...
};
class Monster : public Component {
virtual void initialize(); // concrete implementation for a Monster
virtual void rotate(int x, int y);
};
You may then consider the "command" design pattern. The general idea would be:
class Command { // generic interface for commands
Component *receiver;
public:
Command(Component *receiver);
virtual ~Command();
virtual void execute();
};
class InitializeCommand : Command { // a specific command
public:
InitializeCommand (Component *receiver /* + additional command specific parameters */); // specific constructor with all needed parameters
void execute() {
// use the parameters and do the common operations
receiver->initialize(); // polymorphically call the object operations
// ...
}
};
The rest depends of your global design.
You could for example design a factory that would create the commands based on the events that are processed and execute these:
if (event==...) {
// todo: find object pointed to by the object
Command c = myfactory_for_event (object, parameters);
c.execute();
}
Of if your xml file is meant to configure an object, then you read the file, create specific commands, and store them in an event map that associates an event name to a concrete command:
map<string,Command*> commands;
In this case, the event processing would be something like:
myobject["initialize"]->execute();
So no one knows if there is any way to do this? Obviously there are hack ways. Multiple integration, multiple factories etc. I could ONLY have responses to events done as Command objects but that seems like a weird solution...because there is no runtime information available I have to encapsulate each INDIVIDUAL function in its own class..waste of memory if you ask me...Just realized how weird that sounds. Basically what I meant is for each funtion I wanted to map to an event I would have to create an entire new class (same as the command pattern I am already using to map keys). Would be much easier if I could just provide a function address instead of allocating and deallocating memory for ever individual action but no one seems to have an answer.

Notification Center in C++

After programming for sometime with the iOS and Mac objective C frameworks, I have come to love the generic notification pattern implemented by the NSNotificationCenter and NSNotification classes. Coming back to C++, which has always been my language of choice for most things, I find myself trying to replicate this pattern and believe there should really already be a generic implementation of similar C++ classes offering support for it out there.
It does seem like the pattern is somewhat more difficult to implement in C++ than Objective C because of the more dynamic nature of the later, but it seems far from impossible. I've looked through the boost libraries as they are generally awesome and was sad not to find my luck there. Although the boost::bind, boost::lamda, boost::function seem like they do most of the work. Have I missed something obvious? Is there anything already existing out there that would allow me to easily replicate NSNotification/NSNotificationCenter behaviour?
In theory you could create a class that has a vector of function pointers to call when a certain notification is called - A class that has a dictionary where the objects are the vectors of functions to call when a notification is pushed
In addition to the boost packages mentioned in other answers, another option is poco::NotificationCenter.
This implementation is closer to the Cocoa notification framework, as specifically discussed on Poco's documentation:
The NotificationCenter class is basically a C++ implementation of the
NSNotificationCenter class found in Apple's Cocoa (or OpenStep).
Following #anno's recommendation to look at boot::signal, it does after examination seem like a possible option although it is, as expected, not as straight-forward as the objective C solutions. Looking through the boost::signal tutorial, I thought I would go through the most relevant aspects for the problem at hand.
To create notification senders:
Consider a simple news delivery service, where clients connect to a news provider that then sends news to all connected clients as information arrives. The news delivery service may be constructed like this:
class NewsItem { /* ... */ };
boost::signal<void (const NewsItem&)> deliverNews;
The objective of deliverNews is to inform observers that a NewsItem has been generated.
Observers can be added as follows (using the boost::bind library):
Clients that wish to receive news updates need only connect a function object that can receive news items to the deliverNews signal. For instance, we may have a special message area in our application specifically for news, e.g.,:
struct NewsMessageArea : public MessageArea
{
public:
// ...
void displayNews(const NewsItem& news) const
{
messageText = news.text();
update();
}
};
// ...
NewsMessageArea newsMessageArea = new NewsMessageArea(/* ... */);
// ...
deliverNews.connect(boost::bind(&NewsMessageArea::displayNews, newsMessageArea, _1));
To address the problem of removing observers which have been deallocated from the list, boost::signal offers the following solution
However, what if the user closes the news message area, destroying the
newsMessageArea object that deliverNews knows about? Most likely, a
segmentation fault will occur. However, with Boost.Signals one need
only make NewsMessageArea trackable, and the slot involving
newsMessageArea will be disconnected when newsMessageArea is
destroyed. The NewsMessageArea class is made trackable by deriving
publicly from the boost::signals::trackable class, e.g.:
struct NewsMessageArea : public MessageArea, public boost::signals::trackable
{
// ...
};
At this time there is a significant limitation to the use of trackable
objects in making slot connections: function objects built using
Boost.Bind are understood, such that pointers or references to
trackable objects passed to boost::bind will be found and tracked.

Passing pointer of calling object (this) as argument to method of another instantiated method in C++

I'm reviewing some code and I have stumbled many times on examples as described in title. THen this passed object is referenced in calling outside methods from second object, even changed somewhere else and then again used by reference in another methods.
THe weirdest thing is that the second object calls methods from passed first object that created second anyway.
I haven't done similar stuff yet, but I since I am relatively new to C++ I allow possibility that people feel very free in coding with language with so many options...
However, the main question is: is that common practice? Is there any technical reason for not doing such stuff?
I have added a short example:
TypeReturned *ClassB::GetSomething( ClassA *objectA)   
{
        someMethod(wm);
        ClassC *objectC = new ClassC(objectA->method());
    PCS->method(……, &objectA->someMethod(), objectA);
}
This method is called from objectA.
First call is quite normal. The second and the third would be more readable to solve with simpe passing needing parameters, not the complete classes and callbacks.
I can also say, that those those 2 classes do not really communicate to each other and don't have cross-references.
Perhaps main question should be divided into more: is this usual and practical workaround to pass itself to another object in C++?
It is both usual and practical. Quite often it's the most natural way to achieve something. For example if you want a parent-child navigable from both ends, it's easiest for the parent object to pass itself (this) to the child object after creation so that it stores the reference to parent. Registering self for callback (as in the observer pattern) is another example.
This is useful in general, not something specific to C++.
AFAIK it's perfectly OK technically and happens all the time. Sometimes it's the "best" way and, believe it or not, the clearest way.
pete
I think (Although, I can't tell and am happy to be shown wrong) that what you are describing is a scheme similair to double dispatch (Example in C#). If I am correct you are seeing calls like:
class LivenessPingMessage : public Message {
public:
void accept(Controller& c) {
c.visit(this);
}
}
class Controller {
public:
handleNetworkQueue() {
while (true) {
Messages::Message* m = networkLayer->getNextMessage();
if (m != NULL) {
m->accept(*this);
}
}
}
void visit(Messages::LivenessPingMessage* m) {
//Do something
}
}
class Message {
public:
virtual void accept(Controller& c) = 0;
}
This allows the class Controller to handle messages by calling the virtual accept() method they have. These messages then use the pointer to Controller they have been given to call the overloaded method visit(Message m).
This means that Messages only need to know about Controllers, not any other details about the tasks they are supposed to complete. The Controller contains all the logic needed to deal with the Message appropriately.
It is common amongst people who like double dispatch and is a recognised design model.