Interruption, global variables and MainWindow in Qt - c++

A friend and I are working on a simple synthesizer in C++. We have working oscillator, filter and envelope classes and are able to output some sounds using Portaudio libraries.
We are now working on the graphic interface with Qt Creator but are quite confused with how to organise everything. Indeed, portaudio uses a callback function to fill the buffer and to do so, it needs to access the getValue() method of the ocsillator or the process() method of the filter. But at the moment, we declared our oscillator object and our filter object as pointers inside the MainWindow class. We thus cannot access their methods in the callback function.
More informations on the callback function of portaudio can be found here.
Here are 2 solutions that I thought of :
Putting all the synthesiser objects (osc, filter etc) as globals, so that I can access them in my callback function
Putting the callback function and all the sound-related functions in main.cpp instead of mainwindow.cpp and having the MainWindow object as global, so that I can access its attributes (i.e. the oscillator etc. objects) in the callback function.
I don't really know which solution is the best, or if there is any that would work better...

Related

How to access non-static Qt Ui function from a static member function of a different class?

So me and my friends are developing Connect4 in C++. At first we elaborated the logic behind the game in a Visual Studio Console Application. We came up with 3 classes, "Logic", "GameUi" (That name is probably not suitable) and "Gui". (I should mention that all members off these classes are static members - so no instances)
Once the logic worked it was my job to tranfer it to Qt. And here's the problem:
So basically once the player has done an input (aka. The Player has chosen a column in which he wants to throw the slice (?) in) the Logic class processes this input and updates the vector in which we store the field. After this Logic calls the GamUi class, which should then call a function in the Gui class (Note that the Gui class is now the Qt class). The Problem with that is that I can't call a non-static function in the Qt class to change the Ui from a static function from a different class.
At first I thought about making the Ui public, which is according to the internet not a good programming exercise.
Thank you very much in advance
Ps: Please don't judge me for my non-native-speaker-english and my not very good c++ skills.
Assuming GUI is a singleton, you might code a static GUI::instance() method that returns a pointer to itself. Call it from anywhere and you have your pointer. Better yet, [inherit from QObject and] use signals and slots.

Lua Wrapper Class - Exposing c++ static methods to Lua through a DLL

I finally got into a problem that I can't find a solution here. I'm using a Lua Wrapper Class found in here http://lua-users.org/wiki/CppConvenientLuaWrapperClass. We've been able to expose a complete API plus more other funcionalities like serial communication and on.
The concept behind this Lua Wrapper is that you expose every method before compiling so when you're running your programm all methods will be added to the Lua Stack and in that way you can execute them. The idea now is to build kind of a Dll in order to complete this process of exposing methods. This way you won't needed to release a version with all exposed methods instead you load them trough multiple dll files.
I've tried to create another table and register other methods in that table, but with that, previous exposed methods stop working.
The other way around I can think of, is to create a dll but in C that contains all desirable methods and load it directly to Lua. But I think the other way would be better.
Have you been able to do something similar ? Am I having some wrong concept?
Thanks
Humm... I really don't want to change our wrapper at this time. I think I could manage to do it, sort of. Instead of adding a new table for the plugin functions, I've added a new sub-table tha will contain the functions names and cClosures to be called from Lua.
So at the end we should have:
application.functionName()
application.plugin.functionName()
Even if it work this way it will do fine.
Now I wonder how can we reference the lua_settable when exposing the functions to be added to application[plugin][pluginFunction] instead of aplication[pluginFunction]?!
This is how the normal functions are exposed:
//mState is a pointer to a Lua_State
lua_pushstring( mState, functionName );
//methodDesc is a pointer to an object that describes the function arguments/returns
lua_pushlightuserdata( mState, methodDesc );
//exposeMethodProxy is the method that is responsible for conneting lua c-calls to the c-functions
lua_pushcclosure( mState, exposedMethodProxy, 1 );
//mMethodTableIndex is a member variable that contains the index of the table tha hold all exposed functions
lua_settable( mState, mMethodTableIndex );
Any ideas on how I could achieve adding the cclosures not to the main table(at mMethodTableIndex) as mainTable[functionName] but at maintable[plugin][functionNane].?
I'm not sure, you're clear on what you want to do. A typical way to extend lua is to write a DLL with a single method that uses the Lua API to register your C++ types and C functions. To conviniently bind C++ functions and classes, you could use LuaBridge. An example of such binding is here: https://github.com/d-led/xerceslua
The header for the DLL of the xerceslua module contains only one function:
#include <lua.hpp>
void register_xerceslua (lua_State* L);
inside the implementation LuaBridge is used to bind to C++:
#include "xerceslua_lib.h"
#include <lua.hpp>
#include <LuaBridge.h>
void register_xerceslua (lua_State* L) {
...
luabridge::getGlobalNamespace(L)
.beginNamespace("xerces")
.addVariable("version",&version,false)
...
in Lua you can then access the exposed C++ API:
assert(require 'xerceslua')
local parser=xerces.XercesDOMParser()
parser:loadGrammar("Employee.dtd",xerces.GrammarType.DTDGrammarType)
You can use Lua both as an embedded scripting language, where you can execute lua from within your software, or you could use it as an extensible scripting language, extending it using the method shown above. Both are valid, but you have to consider, what exactly you are trying to do.

Use non-member method as a callback in GLUT [duplicate]

This question already has answers here:
How to pass a class method as a GLUT callback?
(5 answers)
Closed 10 years ago.
I am trying to pass a function to GLUT call back glutSpecialFunc.
It's working perfectly when I try to pass a static function(specialKeyProcessor) to it.
When I moved this function to a class(KeyBoardMovement) specialized in processing keyboard-related functions it does not seem to work:
....
KeyboardMovement keyboard;
....
glutSpecialFunc(keyboard.specialKeyProcessor);
The error pops out: Reference to non-static member function must be called.
I dont understand this error because I cant see any difference between the same function placed in different places.
The glutSpecialFunc function sets a per-window callback. If you are using OpenGLUT, it also allows you to associate some data with each window using glutSetWindowData.
Therefore, you can make a global shim function like this:
void specialKeyProcessor(int key, int x, int y) {
KeyboardMovement *keyboard = static_cast<KeyboardMovement *>(glutGetWindowData());
keyboard->specialKeyProcessor(key, x, y);
}
and associate your keyboard handler using glutGetWindowData:
glutSetWindowData(static_cast<void *>(&keyboard));
If you need to store more than one piece of window data, you can store a pointer to a window-specific struct with fields for each window-specific data.
If you aren't using OpenGLUT, you can consider making a std::map mapping window IDs to your global data. Then you can take a similar approach to the above to have window-specific data.
C++ doesn't support closures, which means it can not turn a class instance, together with a method into a function pointer that when called will execute the method of the class instance.
Unfortunately GLUT doesn't support data aware callbacks, like most other C callbacks API do. So it's either write a wrapper function, that will call on a global instance of your class, or well, employ some really dirty tricks using a library called "ffcall" that can practically create new functions at runtime, which can be parametized and act as a closure you can pass to GLUT. But that's really dark stuff and the right thing would be to ditch GLUT.

c++ GUI Events/Messaging Design

So, I'm making a simple game using DirectX 9 and C++. I looked at the SDK's GUI, but I think I can implement something simpler.
All I want are windows, labels, buttons, textboxes, and checkboxes.
I've created a base class GUIObject, that all inherit from. It includes basics like size and focus and whatnot. Then the derived classes, GUILabel for example, all define render(), update() and whatnot.
My question is how to handle events, like clicks? I had it working with GUILabel::Click() defining every possibility based on the current instance's text member value. It felt wrong and I realized that every single label that needed to be clicked would have to be defined in the GUILabel class. I'd like to move that to each game state's code.
So, I briefly tried making the GUILabel::Click() take a function pointer as an argument. But then I realized I needed to have the state's class member method as static (not really possible, unless everything in it is static as well, right?) or also pass it a GUIObject class as well. Is that the way to go?
Could I define a derivation of GUILabel (or button, or whatnot) within a game state and just override whichever actions I needed? And then do that for whatever controls I need in that state?
What is the proper way to implement event handling?
You might want to look into using a signaling library such as boost::signals to allow you the flexibility of defining the interface between your GUI objects and the underlying events that each callback will trigger. It can also come in handy for the reverse relationship where you need GUI elements such as status indicators, etc. to respond to underlying events.
For callbacks/click events i would go with boost::function/boost::bind.
In my GUI framework I used to have two different abstract classes InputHandler and Renderable for handling touches and rendering. This leads to a design where components which don't need to be clickable (like UILabel) wont need to implement useless methods.
HTH,
Alex

C++ Callbacks? Should I use Member Func Pointers/Delegates/Events?

I am entering a realm that is new to me, but basically I need to implement callbacks in C++. I am designing a toolkit for myself to use to simplify my life. Basically it is a .dll plugin that will be exposing a lot of functions to my other .dll plugins.
One of these functions is HookEvent(const char *event_name, void *callback) which will allow me to hook different events that get fired. Here would be an example...
Example_Plugin1.dll does HookEvent("player_spawn", &Plugin1::Event_PlayerSpawn);
Example_Plugin2.dll does HookEvent("player_spawn", &Plugin2::Event_PlayerSpawn);
I need to figure out the best (and preferably easiest) method of setting up a callbacks system that will work well for this. I have been reading up on C++ callbacks for a few hours now, and found quite a few different approaches.
I assume the easiest thing to do would be make a template, and use typedef bool (ClassName::*EventHookCallback)(IGameEvent, bool); After that, I am a bit foggy.
I also read that Delegates or a .NET style events system are other possible approaches. I am already somewhat confused, so I don't want to confuse myself more, but figured it was worth asking.
Here is a link to the C++ .NET style events system I was reading about.
http://cratonica.wordpress.com/2010/02/19/implementing-c-net-events-in-c/
So what do you guys suggest? Any tips as far as implementing it would be most appreciated.
If you want generalized event firing Boost.Signals2 might be applicable.
The Boost.Signals2 library is an
implementation of a managed signals
and slots system. Signals represent
callbacks with multiple targets, and
are also called publishers or events
in similar systems. Signals are
connected to some set of slots, which
are callback receivers (also called
event targets or subscribers), which
are called when the signal is
"emitted."
Even if you don't need this level of flexibility you should be able to simplify the function binding in your code using Boost.Bind, or the C++0x equivalents.
EDIT:
There's an excellent discussion from Herb Sutter of the issues you could face here. You could use this for guidance if you decide you don't need the full Boost feature set, and so roll your own.
How about using Qt Signal and Slot? It does what callbacks do but without the messiness of making anything not part of your callback parameters global.
Boost.Signals would be my choice, combined with things like boost::bind and Boost.Function.
I would use an abstract base class as a plugin interface. (And in fact, I have used a pattern like the one below before.)
Library, PluginIfc.h:
class PluginIfc {
public:
virtual ~PluginIfc() = 0;
virtual bool EventCallback(const char* event_name, IGameEvent, bool) = 0;
};
// For Windows, add dllexport/dllimport magic to this declaration.
// This is the only symbol you will look up from the plugin and invoke.
extern "C" PluginIfc* GetPlugin();
Plugin:
#include <PluginIfc.h>
class Plugin1 : public PluginIfc {
public:
virtual bool EventCallback(const char* event_name, IGameEvent, bool);
Plugin1& get() { return the_plugin_obj; }
bool Event_PlayerSpawn(IGameEvent, bool);
// ...
private:
std::vector<std::string> _some_member;
static Plugin1 the_plugin_obj; // constructed when plugin loaded
};
Plugin1 Plugin1::the_plugin_obj;
PluginIfc* GetPlugin() { return &Plugin1::get(); }
This way, your plugin classes can easily have members, and C++'s virtual call mechanism takes care of giving you a good this pointer in EventCallback.
It may be tempting to make a virtual method per event type, say just make Event_PlayerSpawn and similar methods virtual. But then whenever you want to add an event type, if this means changing class PluginIfc, your old compiled plugins are no longer compatible. So it's safer to use a string event identifier (for extensibility) and have the main callback sort events off to more specific methods.
The major drawback here (as compared to a signal-slot type implementation) is that all callbacks must take the same set of arguments. But your question sounded like that would be adequate. And it's often possible to work within that limitation by making sure the set of arguments is very flexible, using strings to be parsed or Any-style objects.
Sounds like you might be interested in how to build your own plugin framework. The problems you'll encounter are likely the same. Have a look at this nice Dr Dobbs article Building Your Own Plugin Framework.
Hope this helps!
Implementing your own callback system is non-trivial.
My understanding is that your aim is to map event types to specific callback functions.
E.g. if "player_spawn" event is risen the &Plugin1::Event_PlayerSpawn will be called.
So what you should do is the following:
1) Define all the events of interest. Make them as generic as possible. They can
encapsulate any information you need
2) Create a Registrar. I.e. a class that all modules register their interest for specific
methods. E.g. Registrar.register(player_spawn,this,Event_PlayerSpawn);
3) Registrar has a queue of all subscribers.
4) You can also have a uniform interface for the modules. I.e. all module implement a specific function but based on event's data can do different things
5) When an event occurs, all the subscribers interested for the specific event get notified by calling the appropriate function
6)Subscriber can de-register when ever is need
Hope this helps.