Reputation: 34185
My Application is a Graphics Application written in C++ using OpenGL. I need to use some libraries like GLFW, GLEW and GLM. But you don't need to know about these libraries or OpenGL to answer this question. The point is that all these libraries are written in C so there is no object orientation.
I ran into troubles because of that multiple times. For example currently I have to pass a function, espacially for the resize event of my window, as parameter to GLEW. It expects a static function because there are no classes in C. And reveals the problem that I can't modify any class member in this function. (And I couldn't handle it to provide a global pointer to that class...)
Because of the fact that I want to stay object orientated I had to restructurize my code several times recently. And I am sad of it now.
So are there any approaches or guidelines for handling such object orientated projects using libraries without object orientated support?
Upvotes: 0
Views: 74
Reputation: 36143
Many times the C library lets you pass in a context pointer/reference constant, generally of type void *
or const void *
. Your callback is then passed this argument. This is to let you thread state through to the callback. You can use this to pass through the object you wish to use.
I've seen this done by declaring a static member function, making that the target of the callback, and then bouncing to a proper member function therefrom, something like:
/*static*/ int Class::_callback(void *ctx, int callback_arg) {
Class *me = (Class *)ctx;
return me->callback(callback_arg);
}
int Class::callback(int callback_arg) {
return this->fCount;
}
Upvotes: 1