I'm writing a GLFW app, in which I've wrapped the function calls into a simple class. I'm having trouble setting the key callback.
My class is defined as:
class GAME
{
private:
bool running;
public:
GAME();
int execute();
void events(int, int);
int loop();
int render();
};
The execute function is:
int GAME::execute()
{
glfwOpenWindow(640, 320, 8, 8, 8, 8, 0, 0, GLFW_WINDOW);
glfwSetWindowTitle("Viraj");
glfwSetKeyCallback(events);
running = true;
while(glfwGetWindowParam(GLFW_OPENED))
{
glfwPollEvents();
loop();
render();
}
return 0;
}
Compiling the following code on Visual Studio 2010 gives the error:
error C3867: 'GAME::events': function call missing argument list; use '&GAME::events' to create a pointer to member
Using &GAME::events gives:
error C2664: 'glfwSetKeyCallback' : cannot convert parameter 1 from 'void (__thiscall GAME::* )(int,int)' to 'GLFWkeyfun' 1> There is no context in which this conversion is possible
The code examples provided in the other answers don't describe how to redirect your callback to a per-object member function, with possibly any number of objects. Making your class a singleton will constrain your design and will not scale to multiple glfw windows.
The scalable solution is to set the glfw window user pointer to your object and then fetch it in the callback, and call the member function :
class MyGlWindow
{
public:
void mouseButtonPressed();
};
void makeWindow()
{
GLFWwindow* glfwWindow;
MyGlWindow* myWindow;
/* ... Initialize everything here ... */
glfwSetWindowUserPointer(glfwWindow, myWindow);
auto func = [](GLFWwindow* w, int, int, int)
{
static_cast<MyGlWindow*>(glfwGetWindowUserPointer(w))->mouseButtonPressed( /* ... */ );
}
glfwSetMouseButtonCallback(glfwWindow, func);
}
This solution is shorter and will work for any number of windows.
I also ran into this problem with another glfw callback function, but I didn't want to declare my class method as static, because I needed to access the member variables within. So I tried std::function and std::bind for giving me the ability to bind an instance method as the callback function, but unfortunately it's not an option when working with C callbacks.
The answer to this problem is also stated in the GLFW FAQ "How do I use C++ methods as callbacks":
You cannot use regular methods as callbacks, as GLFW is a C library
and doesn’t know about objects and this pointers. If you wish to
receive callbacks to a C++ object, use static methods or regular functions as callbacks, store the pointer to the object you wish to
call in some location reachable from the callbacks and use it to call
methods on your object.
However, this encouraged me to apply the Singleton pattern for my callback class and integrate it as following:
the callback method of my class is still static, so it can be specified/used as glfw callback
this static callback method makes use of the singleton and passes the callback parameters to an instance method
this instance method actually handles the callback parameters, with the benefit of being able to access the member variables
This is what it looks like:
// Input.h (the actual callback class for glfwSetMouseButtonCallback)
class Input
{
public:
static Input& getInstance() // Singleton is accessed via getInstance()
{
static Input instance; // lazy singleton, instantiated on first use
return instance;
}
static void mouseButtonCallback(int key, int action) // this method is specified as glfw callback
{
//here we access the instance via the singleton pattern and forward the callback to the instance method
getInstance().mouseButtonCallbackImpl(key, action);
}
void mouseButtonCallbackImpl(int key, int action) //this is the actual implementation of the callback method
{
//the callback is handled in this instance method
//... [CODE here]
}
private:
Input(void) // private constructor necessary to allow only 1 instance
{
}
Input(Input const&); // prevent copies
void operator=(Input const&); // prevent assignments
};
and in my main.cpp:
Input &hexmap = Input::getInstance(); // initialize the singleton
//The glfw callback is set up as follows:
glfwSetMouseButtonCallback( &Input::mouseButtonCallback); // specifying the static callback method, which internally forwards it to the instance method
There is a C++ syntax for pointing to class member methods but you cannot pass them to a C style API. C understands function calls and every non-static object method, taking your events as an example, looks like this thinking in C terms: void events(void* this, int, int); meaning that every method apart from the standard arguments also gets a this pointer silently passed.
To make your events C compatible make it static void events(int, int);. This way it will follow the C calling semantics - it will not require a this pointer getting passed. You have to also somehow pass your object to this callback in some other manner (if you need this object's data in the callback).
I had the same problem and after reading this thread I came up with a similar solution. I think it is a bit cleaner this way. It's based on static function but it is nested inside the class where we set all things.
Header looks like this:
class Application
{
public:
...
private:
...
void MousePositionCallback(GLFWwindow* window, double positionX, double positionY);
void KeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
...
class GLFWCallbackWrapper
{
public:
GLFWCallbackWrapper() = delete;
GLFWCallbackWrapper(const GLFWCallbackWrapper&) = delete;
GLFWCallbackWrapper(GLFWCallbackWrapper&&) = delete;
~GLFWCallbackWrapper() = delete;
static void MousePositionCallback(GLFWwindow* window, double positionX, double positionY);
static void KeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
static void SetApplication(Application *application);
private:
static Application* s_application;
};
};
And the source code:
void Application::GLFWCallbackWrapper::MousePositionCallback(GLFWwindow* window, double positionX, double positionY)
{
s_application->MousePositionCallback(window, positionX, positionY);
}
void Application::GLFWCallbackWrapper::KeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
s_application->KeyboardCallback(window, key, scancode, action, mods);
}
void Application::GLFWCallbackWrapper::SetApplication(Application* application)
{
GLFWCallbackWrapper::s_application = application;
}
Application* Application::GLFWCallbackWrapper::s_application = nullptr;
void Application::MousePositionCallback(GLFWwindow* window, double positionX, double positionY)
{
...
}
void Application::KeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
...
}
void Application::SetCallbackFunctions()
{
GLFWCallbackWrapper::SetApplication(this);
glfwSetCursorPosCallback(m_window, GLFWCallbackWrapper::MousePositionCallback);
glfwSetKeyCallback(m_window, GLFWCallbackWrapper::KeyboardCallback);
}
Inspired by N0vember's answer, I present you even more generic and dynamic solution:
class MyGlWindow {
public:
std::function<void(MyGlWindow*)> onClose;
std::function<void(MyGlWindow*, int, int, int)> onMouseClick = [](auto self, int, int, int) { /*some default behavior*/ };
};
void makeWindow() {
GLFWwindow* glfwWindow;
MyGlWindow* myWindow;
/* ... Initialize everything here ... */
glfwSetWindowUserPointer(glfwWindow, myWindow);
#define genericCallback(functionName)\
[](GLFWwindow* window, auto... args) {\
auto pointer = static_cast<MyGlWindow*>(glfwGetWindowUserPointer(window));\
if (pointer->functionName) pointer->functionName(pointer, args...);\
}
glfwSetWindowCloseCallback(glfwWindow, genericCallback(onClose));
glfwSetMouseButtonCallback(glfwWindow, genericCallback(onMouseClick));
myWindow->onMouseClick = [](auto self, int, int, int) {
std::cout << "I'm such a rebel" << std::endl;
self->onClose = [](auto self) {
std::cout << "I'm such a rebellion" << std::endl;
};
};
}
In the header file make the events(int, int) to a static method. That solved the issue for me.
class GAME
{
private:
bool running;
public:
GAME();
int execute();
static void events(int, int); //Changed here to static void
int loop();
int render();
};
This is a useful discussion of possible solutions that helped me with the same problem, and I'm adding my solution in case it proves useful.
Problem Statement
My scenario is more general than the ones addressed by BIC, L.Senionis, and N0vember. In particular, my use case requires:
Generally, instance's data must be accessible to the callback
Many applications can be created using a common set of response handlers
In an application, any number of windows may be created
The set of callbacks attached to each window should be mixed and matched from a certain library of possible responders.
Proposed Solution Usage
The simple singleton design no longer solves the problem. Instead, I provide a GLFWResponder superclass that handles all of the setup complexity. In order to use the class and attach response to a window, here is what is required.
// Implement custom responder
class MyResponder : public GLFWResponder {
public:
virtual void cursor_position_callback(GLFWwindow* w, double x, double y) {...}
... override relevant callbacks ...
};
// in main ************************************************
// Assuming initialized GLFWwindow* my_window and my_other_window
MyResponder resp;
MyResponder resp2; // Can be another subclass of GLFWResponder
// Two responders can respond to same window
resp.respond_to(my_window, GLFWResponder::CURSOR_POSITION);
resp2.respond_to(my_window, GLFWResponder::CURSOR_POSITION);
// One responder can respond to multiple windows
resp2.respond_to(my_other_window, GLFWResponder::CURSOR_POSITION);
// One window can have different handlers for different events
resp.respond_to(my_other_window, GLFWResponder::CURSOR_ENTER);
Proposed Solution Implementation
Here is the sketch of the GLFWResponder implementation, fully functional, but with some TODO's. There may be some implications on performance, which I have not yet investigated.
// GLFWResponder.h ************************************************
/**
* Responder superclass that allows subclasses to handle events from multiple
* GLFW windows (which have only C API for callbacks).
* Callbacks are automatically cleaned up when responder goes out of scope.
*/
class GLFWResponder {
public:
virtual ~GLFWResponder();
// Interface -----------------------------------
enum GLFWEventType {
CURSOR_POSITION = 0,
CURSOR_ENTER = 1
// TODO: add support for other callbacks
};
void respond_to(GLFWwindow* window, GLFWEventType event);
bool does_respond_to(GLFWwindow* window, GLFWEventType event) const;
// Subclasses implement ------------------------
virtual void cursor_position_callback(GLFWwindow* window, double xpos, double ypos);
virtual void cursor_enter_callback(GLFWwindow* window, int entered);
// TODO: add support for other callbacks
// Under the hood ------------------------------
static std::set<GLFWResponder*> getResponders(GLFWwindow* windo, GLFWEventType event);
private:
// Windows and events that this instance responds to
std::set<std::pair<GLFWwindow*, GLFWEventType> > enabled_events_;
// Global responders keyed by events they respond to
// (each responder knows which windows it responds to)
static std::map<GLFWEventType, std::set<GLFWResponder*> > responders_;
};
// GLFWResponder.cpp **************************************************
namespace {
void cursor_position_callback_private(GLFWwindow* window, double xpos, double ypos) {
for (GLFWResponder* r : GLFWResponder::getResponders(window, GLFWResponder::CURSOR_POSITION)) {
r->cursor_position_callback(window, xpos, ypos);
}
}
void cursor_enter_callback_private(GLFWwindow* window, int entered) {
for (GLFWResponder* r : GLFWResponder::getResponders(window, GLFWResponder::CURSOR_ENTER)) {
r->cursor_enter_callback(window, entered);
}
}
} // namespace
std::map<GLFWResponder::GLFWEventType, std::set<GLFWResponder*> > GLFWResponder::responders_;
GLFWResponder::~GLFWResponder() {
for (auto& pr : responders_) {
pr.second.erase(this);
}
// TODO: also clean up window's callbacks
}
void GLFWResponder::respond_to(GLFWwindow* window, GLFWResponder::GLFWEventType event) {
enabled_events_.insert(std::make_pair(window, event));
responders_[event].insert(this);
if (event == CURSOR_POSITION) {
glfwSetCursorPosCallback(window, cursor_position_callback_private);
} else if (event == CURSOR_ENTER) {
glfwSetCursorEnterCallback(window, cursor_enter_callback_private);
} else {
// TODO: add support for other callbacks
LOG(FATAL) << "Unknown GLFWResponder event: " << event;
}
}
bool GLFWResponder::does_respond_to(GLFWwindow* window, GLFWEventType event) const {
return enabled_events_.find(std::make_pair(window, event)) != enabled_events_.end();
}
std::set<GLFWResponder*> GLFWResponder::getResponders(
GLFWwindow* window, GLFWEventType event) {
std::set<GLFWResponder*> result;
auto it = responders_.find(event);
if (it != responders_.end()) {
for (GLFWResponder* resp : it->second) {
if (resp->does_respond_to(window, event)) {
result.insert(resp);
}
}
}
return result;
}
void GLFWResponder::cursor_position_callback(
GLFWwindow* window, double xpos, double ypos) {
// TODO: fail with message "GLFWResponder::do_respond called on a subclass that does not implement a handler for that event"
}
void GLFWResponder::cursor_enter_callback(GLFWwindow* window, int entered) {
// TODO: fail with message "GLFWResponder::do_respond called on a subclass that does not implement a handler for that event"
}
Related
I am going from C development to C++ on the STM32 platform and simply cant find a suitable solution for my problem.
Please have a look at the simplified example code attached to this post.
#include <iostream>
#include <functional>
#include <list>
using namespace std;
class Pipeline {
public:
std::list<std::function<void(Pipeline*)>> handlers;
//add handler to list --> works fine
void addHandler(std::function<void(Pipeline*)> handler) {
this->handlers.push_front(handler);
}
void ethernetCallback(void) {
//handle received data and notify all callback subscriptions --> still works fine
// this callback function is normally sitting in a child class of Pipeline
int len = handlers.size();
for (auto const &handler : this->handlers) {
handler(this);
}
}
void removeHandler(std::function<void(Pipeline*)> handler) {
// Here starts the problem. I can not use handlers.remove(handler) here to
// unregister the callback function. I understood why I can't do that,
// but I don't know another way of coding the given situation.
}
};
class Engine {
public:
void callback(Pipeline *p) {
// Gets called when new data arrives
cout<<"I've been called.";
}
void assignPipelineToEngine(Pipeline *p) {
p->addHandler(std::bind(&Engine::callback, this, std::placeholders::_1));
}
};
int main()
{
Engine *e = new Engine();
Pipeline *p = new Pipeline();
e->assignPipelineToEngine(p);
// the ethernet callback function would be called by LWIP if new udp data is available
// calling from here for demo purposes only
p->ethernetCallback();
return 0;
}
The idea is that when the class "Pipeline" receives new data over ethernet, it informs all registered callback functions by calling a method. The callback functions are stored in a std::list. Everything works fine till here, but the problem with this approach is that I can't remove the callback functions from the list, which is required for the project.
I know why I can't simply remove the callback function pointers from the list, but I don't know another approach at the moment.
Probably anybody could give me a hint where I could have a look for solving this problem. All resources I've researched don't really show my specific case.
Thank you all in advance for your support! :)
One option would be to have addHandler return some sort of identifier that can later be passed to removeHandler. For example:
class Pipeline {
public:
std::map<int, std::function<void(Pipeline*)>> handlers;
int nextId = 0;
//add handler to list --> works fine
void addHandler(std::function<void(Pipeline*)> handler) {
handlers[nextId++] = handler;
}
void ethernetCallback(void) {
for (auto const& entry : handlers) {
entry.second(this);
}
}
void removeHandler(int handlerToken) {
handlers.erase(handlerToken);
}
};
class Engine {
public:
void callback(Pipeline *p) {
// Gets called when new data arrives
cout<<"I've been called.";
}
void assignPipelineToEngine(Pipeline *p) {
handlerToken = p->addHandler(
std::bind(
&Engine::callback,
this,
std::placeholders::_1
)
);
}
void unregisterPipelineFromEngine(Pipeline *p) {
p->removeHandler(handlerToken);
}
private:
int handlerToken;
};
Perhaps you could attach an ID to each handler. Very crude variant would just use this address as an ID if you have at most one callback per instance.
#include <functional>
#include <iostream>
#include <list>
using namespace std;
class Pipeline {
public:
using ID_t = void *; // Or use integer-based one...
struct Handler {
std::function<void(Pipeline *)> callback;
ID_t id;
// Not necessary for emplace_front since C++20 due to agreggate ctor
// being considered.
Handler(std::function<void(Pipeline *)> callback, ID_t id)
: callback(std::move(callback)), id(id) {}
};
std::list<Handler> handlers;
// add handler to list --> works fine
void addHandler(std::function<void(Pipeline *)> handler, ID_t id) {
this->handlers.emplace_front(std::move(handler), id);
}
void ethernetCallback(void) {
// handle received data and notify all callback subscriptions --> still
// works fine
// this callback function is normally sitting in a child class of
// Pipeline
int len = handlers.size();
for (auto const &handler : this->handlers) {
handler.callback(this);
}
}
void removeHandler(ID_t id) {
handlers.remove_if([id = id](const Handler &h) { return h.id == id; });
}
};
class Engine {
public:
void callback(Pipeline *p) {
// Gets called when new data arrives
cout << "I've been called.";
}
void assignPipelineToEngine(Pipeline *p) {
//p->addHandler(std::bind(&Engine::callback, this, std::placeholders::_1), this);
//Or with a lambda
p->addHandler([this](Pipeline*p){this->callback(p);},this);
}
void removePipelineFromEngine(Pipeline *p) { p->removeHandler(this); }
};
int main() {
Engine *e = new Engine();
Pipeline *p = new Pipeline();
e->assignPipelineToEngine(p);
// the ethernet callback function would be called by LWIP if new udp data is
// available calling from here for demo purposes only
p->ethernetCallback();
return 0;
}
You might also consider std::map<ID_t,std::function<...>> instead of list, not sure how memory/performance constrained you are.
Obligatory: do not use new, use std::unique_ptr, or better use automatic storage whenever you can. Although in this case a pointer is appropriate for e as you need stable address due to this capture/bind/ID.
std::functions are not comparable as there isn't a good generic way how to define this comparison.
Here is a simple window class (members omitted for brevity):
class window {
public:
window();
window(const std::string& title, const gt::size2d& size, bool visible = true, bool fullscreen = false);
NO_COPY(window);
window(window&& o);
window& operator=(window&& o);
using close_callback = std::function<void()>;
// members omitted ...
private:
struct impl;
struct impl_deleter {
void operator()(impl* impl);
};
std::unique_ptr<impl, impl_deleter> m_pimpl;
close_callback m_close_callback = []() { DD("Close callback"); };
// ...
};
My goal is to call m_close_callback from GLFW window system, and I could implement something like this:
void close_callback_indirection(GLFWwindow* win)
{
gt::window* winptr = static_cast<gt::window*>(glfwGetWindowUserPointer(win));
if (winptr != nullptr) {
winptr->m_close_callback(); // DOES NOT COMPILE
}
}
gt::window::window(const std::string & title, const gt::size2d & size, bool visible, bool fullscreen)
: m_pimpl{ nullptr }, m_close_callback{ []() {} }, m_size_callback{ [](const gt::size2d&) { } }
{
// omitted GLFW and GL initialization here ...
GLFWwindow* win = glfwCreateWindow(size.x, size.y, title.c_str(), nullptr, nullptr);
m_pimpl.reset(new gt::window::impl);
m_pimpl->glfw_win = win;
glfwSetWindowUserPointer(win, this);
glfwSetWindowCloseCallback(win, close_callback_indirection);
// omitted rest ...
}
This, as expected, does not compile with message "'gt::window::m_close_callback': cannot access private member declared in class 'gt::window'".
However if I implement it like this:
gt::window::window(const std::string & title, const gt::size2d & size, bool visible, bool fullscreen)
: m_pimpl{ nullptr }, m_close_callback{ []() {} }, m_size_callback{ [](const gt::size2d&) { } }
{
// omitted GLFW and GL initialization here ...
GLFWwindow* win = glfwCreateWindow(size.x, size.y, title.c_str(), nullptr, nullptr);
m_pimpl.reset(new gt::window::impl);
m_pimpl->glfw_win = win;
glfwSetWindowUserPointer(win, this);
// using lambda instead of function pointer
glfwSetWindowCloseCallback(win, [](GLFWwindow* win) {
gt::window* winptr = static_cast<gt::window*>(glfwGetWindowUserPointer(win));
if (winptr != nullptr) {
// Accessing private member here
winptr->m_close_callback(); // WHY THIS WORKS?
}
});
// omitted rest ...
}
Now it compiles and it works, if I press window close button I can see the debug message.
My understanding is that lambda without capture list can and in this case will be cast to function pointer so I guess that compiler will generate function code somewhere and pass in a pointer to that, but why does it have access to private member of window object? Is the generated function private member of window (or a friend)?
Can I rely on this behavior or is this something that is considered to be undefined?
I am using MSVC++ compiler
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27026.1 for x86
All lambdas have access to whatever is accessible at the point of their declaration. If you create a lambda in a member function of a class, that lambda can access anything that the member function itself would have access to. Always.
When a captureless lambda is converted to a function pointer, the function referred to by that pointer is identical to the lambda itself. Including its accessibility.
I'm trying to create a dynamic VCL control at runtime and assign an event handler to it.
I think I've tried everything to get this to work, but cannot (everything I try generates different errors).
If you could help fill in the question marks in the code below, it would be of great help!
Oh, in case you're wondering why it's in a namespace instead of a class, it's because this is actually a large library that I just kept adding to. When I change it to a class, you'd think it would be fine, but no, it generates a gazillion weird errors.
test.h
namespace TestSpace {
TTimer *time;
AnsiString file;
void __fastcall MyFunc(AnsiString f);
?Declaration for OnTimer event?
}
test.cpp
void __fastcall TestSpace::MyFunc(AnsiString f) {
TestSpace::file = f;
TestSpace::time->OnTimer = ?;
TestSpace::time->Enabled = true;
}
TestSpace::?(TObject* Sender) {
TestSpace::time->Enabled = false;
DeleteFile(TestSpace::file);
}
A VCL event handler is expected to be a non-static member of a class. Your OnTimer handler is not a class member, it is a free-floating function instead (the namespace is not important).
The correct way to solve this issue is to create a class for your OnTimer event handler, and then instantiate that class alongside the TTimer, eg:
test.h
namespace TestSpace {
class TimerEvents {
public:
void __fastcall TimerElapsed(TObject *Sender);
};
TTimer *time;
TimerEvents time_events;
AnsiString file;
void __fastcall MyFunc(AnsiString f);
}
test.cpp
void __fastcall TestSpace::MyFunc(AnsiString f) {
TestSpace::file = f;
TestSpace::time->OnTimer = &(time_events.TimerElapsed);
TestSpace::time->Enabled = true;
}
void __fastcall TestSpace::TimerEvents::TimerElapsed(TObject* Sender) {
// 'this' is the TimerEvents object
// 'Sender' is the TTimer object
TestSpace::time->Enabled = false;
DeleteFile(TestSpace::file);
}
That being said, there is actually an alternative way to use a free-floating function as a VCL event handler like you want, by using the System::TMethod struct:
test.h
namespace TestSpace {
TTimer *time;
AnsiString file;
void __fastcall MyFunc(AnsiString f);
// NOTE: must add an explicit void* parameter to receive
// what is supposed to be a class 'this' pointer...
void __fastcall TimerElapsed(void *This, TObject *Sender);
}
test.cpp
void __fastcall TestSpace::MyFunc(AnsiString f) {
TestSpace::file = f;
TMethod m;
m.Data = ...; // whatever you want to pass to the 'This' parameter, even null...
m.Code = &TestSpace::TimerElapsed;
TestSpace::time->OnTimer = reinterpret_cast<TNotifyEvent&>(m);
TestSpace::time->Enabled = true;
}
void __fastcall TestSpace::TimerElapsed(void *This, TObject* Sender) {
// 'This' is whatever you assigned to TMethod::Data
// 'Sender' is the TTimer object
TestSpace::time->Enabled = false;
DeleteFile(TestSpace::file);
}
I'm trying to register a class member function as a (regular) callback function. Unless I've misunderstood something, this should be possible using std::bind (using C++11). I do this the following way:
std::function<void (GLFWwindow*, unsigned int)> cb = std::bind(&InputManager::charInputCallback, this, std::placeholders::_1, std::placeholders::_2);
My callback function is defined in the following way:
void InputManager::charInputCallback(GLFWwindow* window, unsigned int key)
I'm able to test cb immediately after creating using random data:
cb(NULL, 0x62);
I can confirm that this data is sent correctly to the callback function by printing to the terminal from within it.
However, I want to register this function to GLFW so that the keypresses of the program window gets sent to the callback function. I do that like this:
glfwSetCharCallback(window, (GLFWcharfun) &cb);
Like I said before: calling it manually works just fine. When I register it as a callback though, I get a segmentation fault whenever I press a key and GLFW tries to call the callback function.
Is std::bind not what I'm looking for? Am I using it incorrectly?
Edit:
I don't think this question is a duplicate of How can I pass a class member function as a callback? like it has been identified as. While we're adressing the same problem, I'm asking about this particular solution, using std::bind, which is only mentioned but never explained in one of the answers to the other question.
Here is the function declaration:
GLFWcharfun glfwSetCharCallback ( GLFWwindow * window,
GLFWcharfun cbfun
)
Where GLFWcharfun is defined as typedef void(* GLFWcharfun) (GLFWwindow *, unsigned int)
There is an obvious problem here in that you do not get the opportunity to pass in a 'context' object which will automatically map the callback back to an instance of InputManager. So you will have to perform the mapping manually using the only key you have available - the window pointer.
Here is one strategy...
#include <map>
#include <mutex>
struct GLFWwindow {};
typedef void(* GLFWcharfun) (GLFWwindow *, unsigned int);
GLFWcharfun glfwSetCharCallback ( GLFWwindow * window,
GLFWcharfun cbfun
);
struct InputManager;
struct WindowToInputManager
{
struct impl
{
void associate(GLFWwindow* window, InputManager* manager)
{
auto lock = std::unique_lock<std::mutex>(mutex_);
mapping_[window] = manager;
}
void disassociate(GLFWwindow* window, InputManager* manager)
{
auto lock = std::unique_lock<std::mutex>(mutex_);
mapping_.erase(window);
}
InputManager* find(GLFWwindow* window) const
{
auto lock = std::unique_lock<std::mutex>(mutex_);
auto i = mapping_.find(window);
if (i == mapping_.end())
return nullptr;
else
return i->second;
}
mutable std::mutex mutex_;
std::map<GLFWwindow*, InputManager*> mapping_;
};
static impl& get_impl() {
static impl i {};
return i;
}
void associate(GLFWwindow* window, InputManager* manager)
{
get_impl().associate(window, manager);
}
void disassociate(GLFWwindow* window, InputManager* manager)
{
get_impl().disassociate(window, manager);
}
InputManager* find(GLFWwindow* window)
{
return get_impl().find(window);
}
};
struct InputManager
{
void init()
{
// how to set up the callback?
// first, associate the window with this input manager
callback_mapper_.associate(window_, this);
// now use a proxy as the callback
glfwSetCharCallback(window_, &InputManager::handleCharCallback);
}
static void handleCharCallback(GLFWwindow * window,
unsigned int ch)
{
// proxy locates the handler
if(auto self = callback_mapper_.find(window))
{
self->charInputCallback(window, ch);
}
}
void charInputCallback(GLFWwindow * window,
int ch)
{
// do something here
}
GLFWwindow* window_;
static WindowToInputManager callback_mapper_;
};
Or if you prefer closures:
#include <map>
#include <mutex>
struct GLFWwindow {};
typedef void(* GLFWcharfun) (GLFWwindow *, unsigned int);
GLFWcharfun glfwSetCharCallback ( GLFWwindow * window,
GLFWcharfun cbfun
);
struct InputManager;
struct WindowToInputManager
{
using sig_type = void (GLFWwindow *, unsigned int);
using func_type = std::function<sig_type>;
struct impl
{
void associate(GLFWwindow* window, func_type func)
{
auto lock = std::unique_lock<std::mutex>(mutex_);
mapping_[window] = std::move(func);
}
void disassociate(GLFWwindow* window)
{
auto lock = std::unique_lock<std::mutex>(mutex_);
mapping_.erase(window);
}
const func_type* find(GLFWwindow* window) const
{
auto lock = std::unique_lock<std::mutex>(mutex_);
auto i = mapping_.find(window);
if (i == mapping_.end())
return nullptr;
else
return std::addressof(i->second);
}
mutable std::mutex mutex_;
std::map<GLFWwindow*, func_type> mapping_;
};
static impl& get_impl() {
static impl i {};
return i;
}
template<class F>
void associate(GLFWwindow* window, F&& f)
{
get_impl().associate(window, std::forward<F>(f));
glfwSetCharCallback(window, &WindowToInputManager::handleCharCallback);
}
void disassociate(GLFWwindow* window)
{
// call whatever is the reverse of glfwSetCharCallback here
//
// then remove from the map
get_impl().disassociate(window);
}
const func_type* find(GLFWwindow* window)
{
return get_impl().find(window);
}
static void handleCharCallback(GLFWwindow* w, unsigned int ch)
{
auto f = get_impl().find(w);
// note - possible race here if handler calls disasociate. better to return a copy of the function?
if (f) {
(*f)(w, ch);
}
}
};
struct InputManager
{
void init()
{
callback_mapper_.associate(window_, [this](auto* window, int ch) { this->charInputCallback(window, ch); });
}
void charInputCallback(GLFWwindow * window,
int ch)
{
// do something here
}
GLFWwindow* window_;
WindowToInputManager callback_mapper_;
};
Here is an abstract of my code. I'm trying to use glutSpecialFunc to tell glut to use my KeyPress function
class Car : public WorldObject
{
public:
void KeyPress(int key, int x, int y)
{
}
Car()
{
glutSpecialFunc(&Car::KeyPress); // C2664 error
}
}
The error message I get is:
Error 1 error C2664: 'glutSpecialFunc' : cannot convert parameter 1 from 'void (__thiscall Car::* )(int,int,int)' to 'void (__cdecl *)(int,int,int)' c:\users\thorgeir\desktop\programmingproject1\quickness\quickness\car.cpp 18 Quickness
Your function is a member of a class. When you do something like Car c; c.drive(), that drive() function needs a car to work with. That is the this pointer. So glut can't call that function if it doesn't have a car to work on, it's expecting a free function.
You could make your function static, which would mean the function does not operate on a car. glut will then be able to call it, however I assume you want to manipulate a car. The solution is to make the function pass it's call onto an object, like this:
void key_press(int key, int x, int y)
{
activeCar->KeyPress(key, x, y);
}
Where activeCar is some globally accessible pointer to car. You can do this with some sort of CarManager singleton.
CarManager keeps track of the active car being controlled, so when a key is pressed you can pass it on: CarManager::reference().active_car().KeyPress(key, x, y).
A singleton is an object that has only one globally accessible instance. It is outside the scope of the answer, but you can Google for various resources on creating one. Look up Meyers Singleton for a simple singleton solution.
A different approach is to have a sort of InputManager singleton, and this manager will keep track of a list of objects it should notify of key presses. This can be done in a few ways, the easiest would be something like this:
class InputListener;
class InputManager
{
public:
// ...
void register_listener(InputListener *listener)
{
_listeners.push_back(listener);
}
void unregister_listener(InputListener *listener)
{
_listeners.erase(std::find(_listeners.begin(), _listeners.end(), listener));
}
// ...
private:
// types
typedef std::vector<InputListener*> container;
// global KeyPress function, you can register this in the constructor
// of InputManager, by calling glutSpecialFunc
static void KeyPress(int key, int x, int y)
{
// singleton method to get a reference to the instance
reference().handle_key_press(key, x, y);
}
void handle_key_press(int key, int x, int y) const
{
for (container::const_iterator iter = _listeners.begin();
iter != _listenders.end(), ++iter)
{
iter->KeyPress(key, x, y);
}
}
container _listeners;
};
class InputListener
{
public:
// creation
InputListener(void)
{
// automatically add to manager
InputManager::reference().register_listener(this);
}
virtual ~InputListener(void)
{
// unregister
InputManager::reference().unregister_listener(this);
}
// this will be implemented to handle input
virtual void KeyPress(int key, int x, int y) = 0;
};
class Car : public InputListener
{
// implement input handler
void KeyPress(int key, int x, int y)
{
// ...
}
};
Of course feel free to ask more questions if this doesn't make sense.
What I ended up doing was
Adding:
virtual void KeyPress(int key, int x, int y) {};
to the WorldObject class
And bubble the event to the Car.
void KeyPressed(int key, int x, int y)
{
KeyPress(key,x,y);
list<WorldObject*>::iterator iterator = ChildObjects.begin();
while(iterator != ChildObjects.end())
{
(*iterator)->KeyPressed(key,x,y);
iterator++;
}
}