Best Way C++ Eventing Handling on iPhone and other mobile devices - c++

I am writing a C++ library that will need to do some eventing handling. I intend to call this in and Android environment using JNI, and I also intend to call it from a iPhone application as well. So I want to know the best C++ library or solution for event handling? I want MIT or BSD type license. Or maybe I could write it in objective C and distribute on both types of devices? I don't have a mac so no XCode right now. I need a simple solution, no threading issues, and no GPL etc licenses.Or is there a way to do this in Native C++ easily without a library. I am looking for recommendations on this. One thing it will probably also do is connect to SQLite. Thanks

You can cook up something extremely simple using std::tr1::function. An event could just be a function wrapper:
#include <tr1/functional>
typedef std::tr1::function<void ()> event;
void my_event_handler()
{
// handler code here
}
class C {
public:
void my_method_handler()
{
// handler code here
}
};
int main(int argc, char* argv[])
{
event ev;
ev = &::handler; // assign an event handler
ev(); // fire an event
// same thing, but using a method as a handler
C c;
ev = std::tr1::bind(&C::my_method_handler, &c);
ev();
}
The code above is very portable, I run something like this on iOS, Android, OSX, Windows and cygwin.

Related

C++/Qt: Pass variables between C++ and Qt GUI without the C++ part including the Qt library

Closed:
Thanks everyone for the ideas, will try to work with your provided suggestions so solve my problem!
Problem:
"C++ main" (which CANNOT #include QObject or any Qt lib) gets data, processes the data and passes it into a separate Qt process (Qt GUI in this case).
Data gets visualized within the Qt GUI and provides feedback, e.g. you can send commands to the "C++ main" (like START/STOP MEASUREMENT).
Visualization of the problem in best paint quality.
Question:
Is there any possible way for the "C++ main" to get feedback from the Qt GUI WITHOUT including Qt in "C++ main" in any way? (The "C++ main" runs on an I/O-card which is not able to process/load the Qt lib.)
Thank you in advance for helpful answers!
Without much code on what goes on in your "C++ main" it is difficult to answer. But if you have class with a proper interface that is created in main and then used for the IO you could do something like the following:
class MyIoHandler {
public:
enum Command {START, STOP};
MyIoHandler() {}
void command(Command command) { d_command = command; } // Set the command
void getData(MyData& data) { data = d_data; } // Do a deep copy
private:
void run()
{
while(d_command == START) {
readDataFromIO();
d_data = data;
}
}
Command d_command;
MyData d_data;
};
Then the GUI just need to call the correct functions on the class to interface with the IO handler. There is no need for the main class to know how the GUI looks, but the GUI must know how the class looks.
This is also working on the assumption that they are in the same executable (from the comments) and
You just need to take care about threading etc.
But as mentioned, without some structure or code examples it is very difficult to give a useful answer.
I normally use QUdpSocket (in the Qt world) to talk to my other apps (effectively for IPC). Then your c++ world you can use normal sockets sys/socket.h for the same job. Since your comms is simplistic - i.e. message passing this is quite easy to do. There is some effort creating your c++ / Qt class to handle your UDP, but from then on its really easy.
The main drawback for me is that the two programs have to agree on a port to use (The IP address would be loop back address 127.0.0.1). So you may have a configuration file, or a command line parameter to set this...

Application freeze in 3rd party library call

I am working on a c++ measurement software which uses a 3rd party API for the interface all sensors are connected to. This API is not open source and no debug library is available.
In some occasions, the software freezes when starting to read a value from the interface. While I could not determine what criterions cause the problem and why it only happens sometimes so far, I'd like to intercept the freezing and implement some error handling, which would also allow me to better debug the issue.
In my code, I simply have a call
BOOL result = false;
result = pciadioAIStartConversion(board_index, channel_nr, range);
where, if the error occurs, pciadioAIStartConversion never returns. I am looking for some simple functionality to keep the software running and return if the call takes to long.
I am using the Qt framework (4.8.6) so a possible solution would be using the event system and a QTimer, but therefore the call would need its own thread if I'm not mistaken and that seems like overkill to me.
piezol is right You need a separate thread which can be quite a mess but the good news is that Qt thread framework (which is called QtConcurrent) is really helpful.
Here is an example for running a standard function in a separate thread mantaining control of it.
#include <QDebug>
#include <QThread>
#include <QString>
#include <qtconcurrentrun.h>
#include <QApplication>
using namespace QtConcurrent;
void hello(QString name)
{
qDebug() << "Hello" << name << "from" << QThread::currentThread();
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QFuture<void> f1 = run(hello, QString("Alice"));
QFuture<void> f2 = run(hello, QString("Bob"));
f1.waitForFinished();
f2.waitForFinished();
}

Event system similar to C# (.NET?)

In C# (at least using .NET, but I think it's general), you can create events like this: Understanding events and event handlers in C#.
Is there a similar mechanism for C++?
PS: I've never liked signal/slot system, so please don't suggest it, since I'm already using it and would love to switch to something else.
The event mechanism in C# is really just a formal, language implemented version of the Observer Pattern. This pattern can be implemented in any language, including C++. There are many examples of implementations in C++.
The largest and most common implementation is probably Boost.Signals and Boost.Signals2, though you explicitly mentioned not liking the signal/slot style implementations.
Event.h can be downloaded from the link bellow, it provides a .NET like Event implemented in C++: http://www.codeproject.com/Tips/1069718/Sharp-Tools-A-NET-like-Event-in-Cplusplus
An example of its usage:
#include "Event.h" // This lib consists of only one file, just copy it and include it in your code.
// an example of an application-level component which perform part of the business logic
class Cashier
{
public:
Sharp::Event<void> ShiftStarted; // an event that pass no argument when raised
Sharp::Event<int> MoneyPaid; // will be raised whenever the cashier receives money
void Start(); // called on startup, perform business logic and eventually calls ProcessPayment()
private:
// somewhere along the logic of this class
void ProcessPayment(int amount)
{
// after some processing
MoneyPaid(amount); // this how we raise the event
}
};
// Another application-level component
class Accountant
{
public:
void OnMoneyPaid(int& amount);
};
// The main class that decide on the events flow (who handles which events)
// it is also the owner of the application-level components
class Program
{
// the utility level components(if any)
//(commented)DataStore databaseConnection;
// the application-level components
Cashier cashier1;
Accountant accountant1;
//(commented)AttendanceManager attMan(&databaseConnection) // an example of injecting a utility object
public:
Program()
{
// connect the events of the application-level components to their handlers
cashier1.MoneyPaid += Sharp::EventHandler::Bind( &Accountant::OnMoneyPaid, &accountant1);
}
~Program()
{
// it is recommended to always connect the event handlers in the constructor
// and disconnect in the destructor
cashier1.MoneyPaid -= Sharp::EventHandler::Bind( &Accountant::OnMoneyPaid, &accountant1);
}
void Start()
{
// start business logic, maybe tell all cashiers to start their shift
cashier1.Start();
}
};
void main()
{
Program theProgram;
theProgram.Start();
// as you can see the Cashier and the Accountant know nothing about each other
// You can even remove the Accountant class without affecting the system
// You can add new components (ex: AttendanceManager) without affecting the system
// all you need to change is the part where you connect/disconnect the events
}
If boost is not an option, I implemented events in c++ here. The semantics is almost the same as in .NET . It's a compact implementation but uses quite advanced C++ features: a modern C++11 compiler is required.

c++ multithreaded windows GUI (accessing the forms)

I've written a simple console application using windows sockets to work as a proxy between a server and a client. I decided to make a graphical interface for watching all the in/outgoing packets real time (like a very simple wireshark).
The connection between the server and the client runs on a different thread than the message loop. When the server/client sends a packet, I would like that to be displayed (for example added to a simple text control) immediately.
But since I can not access the forms from other thread than the thread where the message loop is I dont know how to handle this.
I've found several solutions in:
- Managed c++
- C++/CLI
- C#,
but not any without using .NET platform. (I really new to this GUI topic so I am not even sure you can use windows forms without .NET)
Maybe QT + C++ could handle this problem, but any other solution than that? If not is it possible to write a wrapper in C# / Java for the native C++ code?
There must be many applications written in C/C++ which using a GUI, what is the general way to do that?
You are absolutely correct that you cannot access a window in a different thread. The proper way to handle this to post a message using the ::PostMessage Win32 API command (or, if you are using a wrapper library around Win32, whatever function in that wrapper that eventually calls PostMessage). Here's a useful link from Microsoft regarding message queues:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644928(v=vs.85).aspx
There is an alternative one, free and open-source, called Nana C++ Library (http://stdex.sourceforge.net), a pure C++ GUI library.
By using Nana library, the multithreading issue can be fixed easily. There is an article on the multithreading in GUI, it would be a choice for your hobby project.
A quick and dirty Win32 solution would involve a critical section, a text buffer, and a timer in the UI thread.
Define a few globals...
CRITICAL_SECTION bufferLock; // critical section (to be initialized somewhere)
char dataBuffer[65536]; // contains the data that will be sent to the form
int newdata = 0; // how much data we got (this variable must be atomic, int is ok)
char uiDataBuffer[65536]; // data available to the form
int overflow = 0; // just in case...
UI thread timer
void onTimer ()
{
if (overflow)
{
// handle this
}
else
if (newdata) // new data to display
{
// take the lock, copy the data and release the lock quickly
EnterCriticalSection(&bufferLock);
int dataread = newdata;
memcpy(uiDataBuffer, dataBuffer, dataread);
newdata = 0;
LeaveCriticalSection(&bufferLock);
// TODO: append the text in uiDataBuffer[] to your text control
}
}
To be called from the worker thread:
void sendData (char* data, int size)
{
EnterCriticalSection (&bufferLock);
if(size+newdata > 65536)
overflow = 1;
else
{
memcpy(dataBuffer+newdata, data, size);
newdata += size;
}
LeaveCriticalSection (&bufferLock);
}
Code untested. Buffer size and timer frequency are to be adjusted.
It is possible to avoid polling the buffer with the timer by using PostMessage() (with a custom message) to signal the UI that new data is available.
If performance is an issue, data exchange between a producer and a consumer thread can also be performed very efficiently with a lock-free FIFO queue.
PostMessage() alone is not a solution to exchange data between threads.

int main() running constantly

I am brand new to c++ so I apologize if this is a stupid question but I can't seem to find the answer to it.
I have been using Processing for a while now and would like to start using c++ because I heard it is faster and a program I made is too long/dense for Processing to run at a reasonable speed.
In Processing there is a setup void which runs once and then the draw void which runs continuously after that. This is what I am used to and I need it to make remake a program in c++ (a chess AI).
Is there a way to get int main to run continuously? If not can I have it call a function that will run continuously?
Also is there a way to make a window pop up when you run the program which you can draw geometry to? (I will need to make pieces that can be manipulated by a mouse ideally)
I'm using Xcode by the way
main() should typically do your setup and then start the main message-processing loop provided by your toolkit. The message processing loop will run continuously until the user requests your application to quit (or you ask the toolkit to shut down your app).
Your toolkit will call your draw function whenever your window needs to be painted. It will call other functions when user input such as keypresses or mouse clicks happen.
For example, if you were using the GLUT toolkit (for OpenGL, a very popular drawing API supported on Mac, Windows, Linux, and many mobile devices), your main function might look like this (complete tutorial here):
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(500,500);
glutCreateWindow("My First openGL Program");
glutDisplayFunc(render);
glutMainLoop();
}
For Cocoa, the OSX native API, it might look like this (more information and links here):
#import <Cocoa/Cocoa.h>
int main(int argc, const char** argv)
{
return NSApplicationMain(argc, argv);
}
May I suggest that instead of asking very rudimentary questions like this on StackOverflow, you go and invest your time reading one of the thousands of introductory C++ tutorials that are scattered all over the web.
After a couple of hours of reading you'll find that questions like this are answered faster via a Google search.
Good luck with your learning.
You should not try to get main() to run continuously.
You may instead do something like this:
int main() {
while (true) {
//call functions here
}
return 1;
}
In C++, each function is defined by it's call and it's return. For example:
void foo()
{
cout << "hello world!";
return;
}
int main()
{
foo();
return 0;
}
When foo() is called, it runs until the return statement. If we want foo to run for some indeterminate amount of time, we could, for example:
void foo()
{
bool isExiting = false;
char input;
while( isExiting != true )
{
cout << "Exit? ";
cin >> input;
if ( input == 'y' )
{
isExiting = true;
}
return;
}
}
int main()
{
foo();
return 0;
}
This is a kind of ugly example - using cin to a char and whatnot - but it gets the idea across. The while loop will run forever and the innards of it (well, it's logic, anyway) could be replaced with whatever your program needed to do.
Make sense?
There are plenty of options as far as graphics libraries go; you can use SDL, GLUT/OpenGL, DirectX, even good ol' Win32. However, for someone who is relatively new to things as rudimentary as while loops, I suggest that you stay off the C++ for a while, as there are many peculiarities that might prove to be enormous roadblocks. If you really need every ounce of speed, I recommend that you make a DLL with your time-critical algorithms and use it in conjunction with a simpler language that supports DLL's, and provides a relatively developer-friendly interface. Game Maker comes immediately to mind, although I'm sure there are many options out there.
Best of luck.
I'd recommend having a look at Cinder or OpenFrameworks as a neat transition from Processing.org - especially if you're planning on doing multimedia applications (which, if you were using Processing, is likely)
They both provide a very similar layer to that of Processing, and will ease your journey somewhat.
You could also implement your own basic framework on top of SDL if you feel up to it.
As a more general answer to your question, the main() function is basically the same as the setup() function in Processing.org - with the main distinction being that it has to call a (user-provided) draw() function or equivalent.
So a rudimentary equivalent would be:
bool quit = FALSE;
void setup() {
// initialise the screen and so forth
}
void draw() {
// perform some drawing and update tasks
}
int main(int argc, char *argv[]) {
setup();
while (!quit) {
draw();
}
shutdown();
return 0;
}
NB: the above will probably compile, but it would do nothing except loop and potentially bog up your machine since it's not connected to any graphics library and is getting no user input to modify the quit boolean.
finally, I'll quote a section from the Cinder faq:
I’m experienced with Processing, but I
think I’m ready to try something new.
Is Cinder right for me?
Very possibly.
First though, be sure you really need
to move on to Cinder. Have you already
experimented with using an external
IDE like Eclipse? Are you using native
OpenGL calls instead of PGraphics?
What about experimenting with Toxi’s
excellent libraries? You’ll learn some
things that will make an eventual
transition to Cinder much easier, and
as much as we’re into C++, it’s easy
to underestimate how far Processing
can take you. All that said, don’t let
us talk you out of this either — if
you’re excited about learning Cinder,
we’re excited to have you, and we bet
you’ll find it’s easier to get started
than you might imagine.