ActiveX and COM for interprocess communication - c++

I have a closed source program that generates ActiveX events, and I need to modify mine so that these events can be received. So we have two separate executables, and no GUI stuff is used. So far I got to this point, which only works if the event is generated and received by the same process:
[event_source(native)]
class CSource {
public:
__event void MyEvent(int nValue);
};
[event_receiver(native)]
class CReceiver {
public:
void MyHandler(int nValue) { ... }
void hookEvent(CSource* pSource) {
__hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler);
}
void unhookEvent(CSource* pSource) {
__unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler);
}
};
int main() {
CSource source;
CReceiver receiver;
receiver.hookEvent(&source);
__raise source.MyEvent(123);
receiver.unhookEvent(&source);
}
Now, the event_source is in the application I need to interface with. How can I connect the receiver and the source when they are in two separate processes?
Either an explanation or some references will be useful.

You don't want attributed C++ since even though it is still supported, reality is that it has been deprecated since at the very least VS 2008
You need event_receiver(com, not native type since ActiveX events are in question
The items above suggest that you don't use attributes and instead use IDispEventImpl or IDispEventSimpleImpl class to implement receiver of ActiveX control events (the article gives code snippet and references sample project).

Related

Connecting Qt slots and signals from a C++98 interface with no Qt, STL or Boost

I am writing an audio rendering library that takes as input audio buffers, does some magic, then manage playback on a selected device. For this task, I decided to use Qt's QAudioOutput class.
I would like to allow the user to set callbacks when the state of the QAudioOutput object state changes (active, suspended, stopped and idle). I would connect these signals to a signal handler that would call the user-defined callbacks. However, I have the following restriction: no STL, no Qt, no Boost on the library header. I also need to stay compatible with C++98.
Right now, I have 2 solutions (with drawbacks) and I am looking to improve the design. My first solution was:
// library header
class AudioLibrary
{
typedef void ( *Callback )();
void setOnActiveCallback( Callback cb );
};
The problem with this solution is that the client can only pass static functions or non-capturing lambdas. This is too restrictive. Imagine a client who wants to do something as simple as re-enabling a button once playback finished. Not possible if the button is a member variable.
My second solution was that my interface would be an abstract class and contains pure virtual functions that would contain the desired behavior on state change. However, I am not sure this would be much fun for the client of the library...
Is there a cleaner and/or better solution that I ommited to think of?
This sounds like a C style callback.
class AudioLibrary
{
typedef void ( *Callback )( void * );
void setOnActiveCallback( Callback cb, void * context );
// Perhaps also include
template <typename Func>
void setOnActiveCallback( Func & f )
{
setOnActiveCallback( &Func::operator(), &f );
}
};
C-style callbacks without a means to pass context are completely utterly broken and your users will hate you for that. Don't do it. As soon as you have a intptr_t or void* typed context object, you can pass anything you wish to the callback, and quite efficiently at that. Yes, you can pass capturing lambdas, member methods, etc.
E.g.:
class AudioLibrary {
typedef void (*Callback)(void*);
void setOnActiveCallback(Callback cb, void * context);
};
Then:
static void functionCallback(void * context) {
auto f = reinterpret_cast<std::function<void()>*>(context);
f();
}
struct User {
AudoLibrary * m_audio;
std::function<void()> f_onActive{std::bind(&User::onActive, this)};
void onActive();
User(AudioLibrary * audio) : m_audio(audio) {
audio->setOnActiveCallback(functionCallback, &f_member);
}
};

c++ static observer class

I have two programs: a server and a client
class client
{
private:
Network net;
Gui gui;
};
Here's the Network class
class Network
{
public:
void receivePacket(packet)
{
Protocol::readPacket(packet)
}
};
Here's the Gui class
class Gui
{
private:
std::string informations;
public:
void displayInfo();
void updateInformation(information);
};
And here's Protocol
class Protocol
{
static void readPacket(packet)
{
if (packet.command == "refreshGui")
//I need somehow to call GUI::UpdateInformation here and give the information from packet.information
}
};
Protocol is considered as a "static class" which means that in shouldn't be instantiate. So the idea is that, when Protocol::readPacket get a packet from the server, it should be able to send the information to the GUI. However, it's not always the case, so passing a point/reference is not what I'm looking for.
It's not well illustrated but the idea is:
- Protocol::readPacket seek if we need to call GUI
- Protocol shouldn't take another argument, and shouldn't be instantiate.
Someone gave me the advice about using Observer-pattern. Protocol would be the subject and GUI the Observer. However, I couldn't make it without instantiate Protocol.
So is there a way to do it without instantiate Protocol ?
In distributed computing, it is a common pattern for the network manager of a node to receive a message and call a dispatcher associated with the message type. Your need is quite similar. Here is what you could do:
In your Network class, maintain an unordered_map< packet_type, std::function >.
When your program starts, push into that unordered_map an std::pair<"refreshGui", Gui::UpdateInformation>
In Network::receivePacket, retrieve the function from the unordered_map and call it.

How can I provide feedback from a non-Qt C++ library class to a Qt GUI?

I am developing a C++ class library for some computing-intensive tasks (machine vision).
// I am a part of a Qt-agnostic library
class Cruncher
{
/* ... */
public:
void doStuff();
};
Then there's a Qt GUI using that library. I'm creating a worker thread to call the heavy-lifting routines from the library:
// I am a part of a Qt-based GUI which utilizes the library
class Worker : public QThread
{
/* ... */
protected:
virtual void run()
{
/* ... */
Cruncher c;
for (int i = 0; i < count; ++i)
c.doStuff(); // takes some time, and while it's working
// it should communicate status changes which should
// become visible in the GUI
}
};
Now inside doStuff() a lot happens and I want to provide some feedback to the user on what is going on without waiting for doStuff() to return. For one, maybe some finer progress reporting than just increasing the meter by one step after a each call to doStuff(). Also, doStuff() may encounter non-critical failures which let it continue a part of the work, but I'd like a message to appear in the GUI when this happens as Cruncher is working (and Worker is currently busy with a call to doStuff()).
I want the library to remain Qt-independent so I'm not willing to add signals and slots to Cruncher. Any other way to enable it to provide feedback to the GUI to report on its work when it's not a Qt class?
I was considering creating a QTimer which would poll some "status" and "errorMsg" members of Cruncher at fixed intervals while Worker is running, but this seems highly sub-optimal.
I am posting my own answer because though I took #Nim's advice, I'd like the answer to be a little more verbose and hence more useful if someone should have the same problem.
I created the skeleton of a message dispatcher in the library:
// doesn't need to know about Qt
class MessagePort
{
public:
virtual void message(std::string msg) = 0;
};
Next, I added a handle to this object to Cruncher and spiced doStuff() with occasional calls to message():
// now with Super Cow powers!
class Cruncher
{
protected:
MessagePort *msgPort_;
public:
Cruncher(MessagePort *msgPort) : msgPort_(msgPort) {}
void doStuff()
{
while(...)
{
/*...*/
msgPort_->message("Foo caused an overload in Bar!");
}
}
};
Finally, I crafted an implementation of MessagePort inside the GUI using all necessary Qt goodness:
class CruncherMsgCallback : public QObject, public MessagePort
{
Q_OBJECT
public:
CruncherMsgCallback() : QObject(), MessagePort()
{
connect(this, SIGNAL(messageSignal(const QString &)),
GUI, SLOT(messageShow(const QString &)),
Qt::QueuedConnection);
}
virtual void message(std::string msg)
{
emit messageSignal(QString::fromStdString(msg));
}
signals:
void messageSignal(const QString &msg);
};
Finally when the Worker creates an instance of Cruncher, it also gives it a pointer to a working MessagePort:
class Worker
{
protected:
virtual void run()
{
CruncherMsgCallback msgC;
Cruncher c(&msgC); // &msgC works as a pointer to a
// generic MessagePort by upcasting
c.doStuff(); // Cruncher can send messages to the GUI
// from inside doStuff()
}
};
Use a callback function (class) etc, and pass that in during construction. Things you need to report, report via that callback.
You can safely emit signals from the run() method, I think that's the best way to pass information from worker thread to the main thread. Just add the signals to your QThread subclass (avoid adding slots, if you're at all unsure how QThread threading works).
Better make the connections from these signals explicitly queued, to avoid problems. Though the default, automatic connection type should also work and do Queued signal emit, but I think it's better to be explicit in cases like this. Actually also direct signals should work as such, but then you have to take care of thread safety yourself instead of letting Qt handle it for you, and you can't connect to slots which use any of the QtGui classes which only work in the main thread, so it's better to stick to queued connections.
To pass simple information to the run() method, and if immediate reaction is not needed, maybe use a few shared QAtomicInt variables or something like that as flags, which the worker thread checks when convenient. Slightly more complex method, still requiring polling, is to have shared data structure which you protect with mutex. More complex way of communicating to that direction would involve some kind of message queue (just like Qt uses in the event loop of the main thread, when you emit signal to that direction).

Creating a custom message/event with Qt

I have an RPC thread that is calling back to me from that thread. I need to somehow inform Qt that it needs to make a function call from the main thread. In straight Windows I could do this by using a custom message and then posting that message to the message queue, e.g., I could create a WM_CALLFUNCTION message and pass the function pointer through wParam and the parameter (class pointer) through lParam.
Has anyone an idea how I could do this with Qt? I've come across QCustomEvent but I have no idea how to use it or how to process it. Any help would be hugely appreciated!
Edit:
In the end I went with QMetaObject::invokeMethod which works perfectly.
Using custom events generally involves creating your own QEvent subclass, overriding customEvent() in the QObject class that will receive the event (often the main window class) and some code that "posts" the event from your thread to the receiver.
I like to implement the event posting code as a method of the receiver class. That way, the caller only has to know about the recevier object and not any of the "Qt" specifics. The caller will invoke this method which will then essentially post a message to itself. Hopefully the code below will make it clearer.
// MainWindow.h
...
// Define your custom event identifier
const QEvent::Type MY_CUSTOM_EVENT = static_cast<QEvent::Type>(QEvent::User + 1);
// Define your custom event subclass
class MyCustomEvent : public QEvent
{
public:
MyCustomEvent(const int customData1, const int customData2):
QEvent(MY_CUSTOM_EVENT),
m_customData1(customData1),
m_customData2(customData2)
{
}
int getCustomData1() const
{
return m_customData1;
}
int getCustomData2() const
{
return m_customData2;
}
private:
int m_customData1;
int m_customData2;
};
public:
void postMyCustomEvent(const int customData1, const int customData2);
....
protected:
void customEvent(QEvent *event); // This overrides QObject::customEvent()
...
private:
void handleMyCustomEvent(const MyCustomEvent *event);
The customData1 and customData2 are there to demonstrate how you might pass some data along in your event. They don't have to be ints.
// MainWindow.cpp
...
void MainWindow::postMyCustomEvent(const int customData1, const int customData2)
{
// This method (postMyCustomEvent) can be called from any thread
QApplication::postEvent(this, new MyCustomEvent(customData1, customData2));
}
void MainWindow::customEvent(QEvent * event)
{
// When we get here, we've crossed the thread boundary and are now
// executing in the Qt object's thread
if(event->type() == MY_CUSTOM_EVENT)
{
handleMyCustomEvent(static_cast<MyCustomEvent *>(event));
}
// use more else ifs to handle other custom events
}
void MainWindow::handleMyCustomEvent(const MyCustomEvent *event)
{
// Now you can safely do something with your Qt objects.
// Access your custom data using event->getCustomData1() etc.
}
I hope I didn't leave anything out. With this in place, code in some other thread just needs to get a pointer to a MainWindow object (let's call it mainWindow) and call
mainWindow->postMyCustomEvent(1,2);
where, just for our example, 1 and 2 can be any integer data.
In Qt 3, the usual way to communicate
with the GUI thread from a non-GUI
thread was by posting a custom event
to a QObject in the GUI thread. In Qt
4, this still works and can be
generalized to the case where one
thread needs to communicate with any
other thread that has an event loop.
To ease programming, Qt 4 also allows
you to establish signal--slot
connections across threads. Behind the
scenes, these connections are
implemented using an event. If the
signal has any parameters, these are
also stored in the event. Like
previously, if the sender and receiver
live in the same thread, Qt makes a
direct function call.
--
http://doc.qt.nokia.com/qq/qq14-threading.html#signalslotconnectionsacrossthreads

C++: indirect invocation of `delete this` in event driven system (e.g. in GUI application)

I was working for a while with different C++ GUI frameworks (e.g. Qt, wxWidgets, also some proprietary) but cannot decide for myself regarding the topic described below.
As discussed in several questions/answers here, direct use of delete this is valid in C++ (as long as you don't dereference this any more), but it is in most cases not good idea.
But in some cases, object invokes its destructor indirectly. This situation specifically often arise in event drive systems (GUI applications come to mind first).
class Kernel {
public:
void Start() {
_window = new Window();
}
void OnCloseButton() {
if (_window) {
_window->Close();
delete _window;
_window = NULL;
}
private:
MyWindow * _window;
};
class MyWindow
{
public:
MyWindow(Kernel & kernel) : _kernel(&kernel) {
Connect(my_button_close_event, this, OnCloseButtonClicked);
}
OnCloseButtonClicked() {
// This call actually calls destructor of this object.
_kernel->OnCloseButton();
// If we access any fields of Window here, we're going to have problems
}
private:
Kernel * _kernel;
};
Notice: I did not try to compile the code - it may have typos or bad practices. But it should illustrate the idea.
So, the question is: Is it OK to do something like in the example above: the handler of the event calls some other function (method of its owner), which indirectly deletes this?
Or should I better make the Kernel class event aware and connect the event from the button directly to the method in the Kernel and then we do not have this situation of indirect call to delete this.
Thanks in advance.
It's possible to do so since the Window instance is created by the Start() method but it's a bad practice in Object Oriented Programming.