I know that I must pass glfwGetProcAddress function to gladLoadGLLoader function after context was initialized. GLFW documentation says that this function returns the address of the specified function for the CURRENT context. Based on this information, if I want to draw something on another context, I must type
glfwMakeContextCurrent(*window*)
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)
each time I want to change drawing context. However, it is enough to simply change the context with glfwMakeContextCurrent function. Documentation also remarks
The address of a given function is not guaranteed to be the same
between contexts.
But it seems like returned addresses are the actually same between contexts (In windows, at least). The question is, what is true way to do this, in order to achieve stable and portable behaviour?
Technically yes: function pointers retrieved from an OpenGL context are valid only for that specific context. However, for most practical purposes, you can ignore this. If two contexts can share objects, then they almost certainly share function pointers.
If you want to account for those cases where function pointers can't be shared across contexts, the best option is to write a loader specifically for dealing with that eventuality. You could for example modify GLAD to put OpenGL functions in a struct and then load the functions into different structs for different contexts.
Related
When looking through the GLFW reference I came across the glfwGetWindowUserPointer function (and the glfwSetWindowUserPointer function). In the reference it says the following about the user-pointer:
Each window has a user pointer that can be set with glfwSetWindowUserPointer and fetched with glfwGetWindowUserPointer. This can be used for any purpose you need and will not be modified by GLFW throughout the life-time of the window.
Now I wonder for what purpose one could use this?
I am not going to take credit for this answer, as it is not my answer, but the answer of someone else on the GLFW forum.
A UserData field is a fairly common paradigm in C APIs that lets the user access contextual data from within callbacks without needing to make everything global. In essence, it lets you associate an arbitrary piece of data relevant to your program with a glfw window.
If you are trying to use glfw in a program that follows object-oriented design, for example, you can use this pointer to store the address of the instance that is handling a particular window, and forward the callbacks (which have to be static functions, because of the way the API works) to the appropriate member functions.
This question already has answers here:
What is the point of function pointers?
(18 answers)
Closed 4 years ago.
I hope its an extremely repetitive question. And my advance excuse to all the viewers who find it annoying.
Although I am bit experienced programmer, but I cannot justify the use of function pointer over direct call. Scenarios where I unable to find the differences are -
1) callbacks - same can be achieved by direct call.
2) Asynchronous or synchronous event handling - anyway event has to be identified, based on which element no. in function pointer array got updated. But the same can be also done via direct call.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
I really appreciate if someone can explain me using above scenarios with practical and really simple realistic example.
Some more things function pointers are often used for:
Runtime polymorphism: You can define a structure that encapsulates a function pointer, or a pointer to a function table. This enables you to call the specified function at runtime, even for a type of client object that did not exist when your library was written. You can use this to implement multiple dispatch or something like the visitor design pattern in C. This is also how C++ classes and their virtual member functions were originally implemented under the hood.
Closures: These can be structures containing a function pointer and one or more of its arguments.
State Machines: Instead of a switch with a case for each state label, I’ve often found it convenient to give the handler for each state its own function. The current state is the function you’re in, the state transitions are tail-recursive calls, and the program variables are parameters. The state labels then become function pointers, which you might store in a table or return from a function.
Higher-Order Functions: Two examples from the C standard library are qsort() and btree(), which generalize the type of elements and the comparison function.
Low-Level Support: Shared-library loaders, for example, need this.
1) callbacks - same can be achieved by direct call.
Not true. For a direct call, the caller must know the function name and signature when the code is compiled, and can only ever call that one function. A callback is defined at runtime and can be changed dynamically, while the caller need only know the signature, not the name. Moreover each instance of an object may have a different callback, whereas with a direct call, all instances must call the same function.
2) Asynchronous or synchronous event handling - anyway event has to be
identified, based on which element no. in function pointer array got
updated. But the same can be also done via direct call.
Not sure what you mean, but an event handler is simply a kind of callback. The event may be identified by the caller and different call-back handlers called through pointers. Your point only stands if there is one event handler for all event types and the user is to be responsible for identification.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
See (1) and (2) above. Often it is a means to hook platform independent third-party library code into a specific platform without having to deliver source-code or for system events that require user/application-defined handlers.
I would not sweat it however - if all your application requirements can be resolved without using a pointer to a function, then you don't need a pointer to a function. When you need one, you will probably know. You will most likely encounter it when you have to use an API that requires it before you ever implement an interface yourself that does. For example in the standard library the qsort() function requires a pointer to a function in order to define how two objects of arbitrary type are to be ordered - allowing qsort() to support any type of object - it is a way in C of making a function "polymorphic". C++ supports polymorphism directly, so there is often less need for explicit function-pointers in C++ - although internally polymorphism is implemented using function pointers in any case.
There is a concept in programming called DRY -- don't repeat yourself.
Suppose you have 121 buttons in your UI. Each one of them behaves much the same, except when you press the button, a different operation happens.
You can (A) use virtual inheritance to dispatch to the right operation (requiring a class per button), or (B) use a function pointer (or a std::function) stored in the class in order to call the right "on click" handler, or (C) have every single button be a distinct type.
A virtual function is implemented in every compiler I have examined as a complex table that, in the end, is a collection of function pointers.
So your choices are function pointers or generating 121 completely distinct buttons that happen to mostly behave the same.
In any situation where you want to decouple the caller and the called, you must use something akin to a function pointer. There are a ridiculous number of cases, from work queues to thread off tasks, callbacks, etc.
In tiny programs where everything is hard coded, hard coding every call can work. But hard coded stuff like this doesn't scale. When you want to update those 121 buttons each hand-implemented, knowing their points of customization is going to be ridiculously difficult. And they will fall out of sync.
And 121 is a modest number of buttons. What about an app with 10,000? And you want to update every button's behavior to handle touch-based input?
Even more, when you type erase, you can reduce binary size significantly. 121 copies of a class implementing a button is going to take more executable space than 1 class, each of which stores a function pointer or two.
Function pointers are but one type of "type erasure". Type erasure reduces binary size, provides clearer contracts between provider and consumer, and makes it easier to refactor behavior around the type erased data.
Without function pointers, how would you implement a function which calculates the integral of any real-valued function?
typedef double (*Function)(double);
double Integral(Function f, double a, double b);
1) callbacks - same can be achieved by direct call.
Not in all cases, since the caller may not know at compile-time what function must be called. For instance, this is typical in libraries since they cannot know in advance your code.
However, it can also happen in your own code: whenever you want to re-use partially a function, you can either:
Create several versions of that function, each calling a different function. Duplicates code, very bad maintenance. Good performance unless hit by code bloat.
Pass a function pointer (or callable in general in C++). Flexible, less code, performance might suffer in some cases.
Create a set of branches (if/switch chain), if you know in advance the set of possible functions to call. Rigid, but might be faster than a function pointer for small number of branches.
In C++, create a templated version. Same as the first case, but automated; so good maintenance. Code bloat might be an issue.
Factor out the common code so that callers can call whatever they need piece by piece. Sometimes this isn't possible/easy -- specially when parametrizing complex algorithms that you want to keep reusable (e.g. qsort()). In C++, see the STL (Standard Template Library).
2) Asynchronous or synchronous event handling - anyway event has to be identified, based on which element no. in function pointer array got updated. But the same can be also done via direct call.
Some event systems are designed so that you simply configure which function(s) will be triggered when a given event happens. If this is an external library with a C interface, they have no choice but to use function pointers.
Some other systems let you create your own event loop and you fetch the events somehow and do whatever you want with them; so they avoid callbacks.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
See the first case.
Thanks all for actively participating in this discussion. Thanks for giving practical examples like -
1) Implement Library function
2) Look qsort
3) Refer Linux Kernel
4) Generic Heap data structure in C
I feel qsort() void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) s is quite sufficient to clear my 1) & 3) point.
1) callbacks - same can be achieved by direct call.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
Mainly by callbacks - it is a provision of calling a function for which the body is not yet defined. And it expected that the definition of the function will be provided later during run-time. So, compilation won't be hindered due to lack of function definition. Practical use if someone consider above qsort() function. In this the user is responsible for providing the function definition for compare() like -
int compare (int* a, int* b)
{
//User defined body based on problem requirement
}
Lets consider a practical scenario where multiple threads have their respective compare function. In case of direct call every thread need to implement their own sorting function or if a common function then implementation would be much more bulky. But by using the callback method all threads can use same function for sorting, since the sorting algo remain same for all threads.
Considering a layered architecture mainly higher layers have an abstract view of lower layer. So, here if say we have qsort() function [User defined qsort] implemented at application layer and lets say underlying application there is a ADC driver layer which capture sample and provide to application for sorting. Then for application it is not necessary to understand the definition of function responsible for collecting and providing the samples. But application will only focus on obtaining the sample. Hence, that main application won't know which function to call. Respective ADC driver will simply make a call to application using the qsort() and provide needful data.
Regarding 2 point still confused -
2) Asynchronous or synchronous event handling - anyway event has to be identified, based on which element no. in function pointer array got updated. But the same can be also done via direct call.
From above discussion I conclude that if event handlers pointed to some library function, then it need to be implemented via pointer to function. And secondly to create an independent and handy code it is necessary to maintain function pointer. Lets say between application and driver we have an interfacing layer. So, if either application or driver changes anytime it won't affect or very least affect each other. And this interface layer is implemented using pointer to function. But consider below scenario -
int (*fptr[10]) (void) =
{
function1; //function for starting LED
function2; //function for relay operation
.
.
function10; //function for motor control
}
lets say we have GPIO0.0 - GPIO0.10 has been mapped to the function pointer array. i.e. GPIO0.0 - 0th element of fptr
.
.
GPIO0.10 - 10th element of fptr
These GPIO pins has been configured for level triggered interrupt and their respective ISR will update the array element no. i=GPIO_Value; further the scheduler have an thread which will call the function pointer array -
fptr[i]();
Does the use of function pointer is justifiable here??
I am confronted with the fact that sometimes my OpenGL Context gets re-created and my initialization needs to be redone to re-initialize the re-created OpenGL Context.
Right now I am not using many elements, but I mentioned that the IDs (or names or whatchacallthem) that I receive from glGenX are always the same as long as I call the functions in the same order: The first texture I create gets ID 1, the second ID 2 etc. etc.
Is this guaranteed? Because when it is, my internal organization of those OpenGL elements does not need to be re-done, as even though the OpenGL context is another, a reference to texture ID 4 will always point at the correct texture as long as that texture gets re-loaded into the GPU 4th in row?
No, I have never seen a guarantee that the generation of object names will produce the same result each time. The language for the glGen*() calls always sounds like this:
returns n previous unused [..] object names
It never says anything more about how these object names are constructed.
Now, in reality, if you're calling everything in exactly the same sequence, it seems very likely that you're going to get the same names. Software tends to be deterministic in cases like this. But relying on it still sounds like a bad idea to me. It will be one of these things that will probably work for the longest time, and then come back and bite you when you least expect it at the most unfortunate time (like the day before you plan to ship, or after you already shipped).
I don't think this is strictly within the scope of your question, but just to make sure that you're not making any false assumptions: You definitely can't expect the names to be sequential. They are on some platforms/vendors, but not on others. There's also no valid expectation on whether different object types use different names, or if they use the same values. For example, if you call glGenTextures() to create a texture name, and glGenBuffers() to create a buffer name, you could get the same value for the two names.
Also, just to avoid possible misunderstandings: Even if you assume that you already know the names that are going to be generated, you still need to call the glGen*() functions to generate the names if you use the OpenGL Core Profile. It used to be legal to just use any values you wanted for object names, but that's not legal anymore in modern OpenGL. Or in the words of the spec, from the Removed Features appendix:
Application-generated object names - the names of all object types, such as buffer, query, and texture objects, must be generated using the corresponding Gen* commands. Trying to bind an object name not returned by a Gen* command will result in an INVALID_OPERATION error.
This is something that recently crossed my mind, quoting from wikipedia: "To initialize a function pointer, you must give it the address of a function in your program."
So, I can't make it point to an arbitrary memory address but what if i overwrite the memory at the address of the function with a piece of data the same size as before and than invoke it via pointer ? If such data corresponds to an actual function and the two functions have matching signatures the latter should be invoked instead of the first.
Is it theoretically possible ?
I apologize if this is impossible due to some very obvious reason that i should be aware of.
If you're writing something like a JIT, which generates native code on the fly, then yes you could do all of those things.
However, in order to generate native code you obviously need to know some implementation details of the system you're on, including how its function pointers work and what special measures need to be taken for executable code. For one example, on some systems after modifying memory containing code you need to flush the instruction cache before you can safely execute the new code. You can't do any of this portably using standard C or C++.
You might find when you come to overwrite the function, that you can only do it for functions that your program generated at runtime. Functions that are part of the running executable are liable to be marked write-protected by the OS.
The issue you may run into is the Data Execution Prevention. It tries to keep you from executing data as code or allowing code to be written to like data. You can turn it off on Windows. Some compilers/oses may also place code into const-like sections of memory that the OS/hardware protect. The standard says nothing about what should or should not work when you write an array of bytes to a memory location and then call a function that includes jmping to that location. It's all dependent on your hardware and your OS.
While the standard does not provide any guarantees as of what would happen if you make a function pointer that does not refer to a function, in real life and in your particular implementation and knowing the platform you may be able to do that with raw data.
I have seen example programs that created a char array with the appropriate binary code and have it execute by doing careful casting of pointers. So in practice, and in a non-portable way you can achieve that behavior.
It is possible, with caveats given in other answers. You definitely do not want to overwrite memory at some existing function's address with custom code, though. Not only is typically executable memory not writeable, but you have no guarantees as to how the compiler might have used that code. For all you know, the code may be shared by many functions that you think you're not modifying.
So, what you need to do is:
Allocate one or more memory pages from the system.
Write your custom machine code into them.
Mark the pages as non-writable and executable.
Run the code, and there's two ways of doing it:
Cast the address of the pages you got in #1 to a function pointer, and call the pointer.
Execute the code in another thread. You're passing the pointer to code directly to a system API or framework function that starts the thread.
Your question is confusingly worded.
You can reassign function pointers and you can assign them to null. Same with member pointers. Unless you declare them const, you can reassign them and yes the new function will be called instead. You can also assign them to null. The signatures must match exactly. Use std::function instead.
You cannot "overwrite the memory at the address of a function". You probably can indeed do it some way, but just do not. You're writing into your program code and are likely to screw it up badly.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
The OpenGL standard pages states that the OpenGL is callable from C and C++. The API, however, is of course in pure C. As the OpenGL uses for example a lot of enumerations, using enum-classes (from C++11) could greatly reduce number of errors and make the API more feasible for beginners. It could be seen that lot of the bindings like OpenTK (for C#) are created; creating good C++ API shouldn't be much harder.
I weren't able to find anything that was more than an obscure wrapper, hence my questions:
Is there a well-known C++ wrapper using C++11 facilities for OpenGL? and if not,
Is something like this planned by anyone well-known (which especially means the Khronos)?
The whole way OpenGL works does not really well map to OOP: http://www.opengl.org/wiki/Common_Mistakes#The_Object_Oriented_Language_Problem
What's not stated in this article is the context affinity problem. In OpenGL everything happens on the context, so a class "Texture", to be correct would be nothing more than a glorifed handle to be used with the context.
This is wrong:
class Texture {
/* ... */
public:
void bind();
}
It would only work if the texture was part of the currently active context.
This is no better either:
class Texture {
/* ... */
public:
void bind(Context &ctx);
}
The texture still must be part of the context ctx, and it would only work, if ctx was active at the moment.
So what about this:
class Context {
/* ... */
public:
void bindTextureToUnit(TextureUnit &tu, Texture &t);
};
Better, but still not correct as the context must be the one currently active in the current thread. You may think "oh, I'll just throw an exception if context is not active". Please don't do this.
So what about this
class ActiveContext : Context {
/* ... */
public:
void bindTextureToUnit(TextureUnit &tu, Texture &t);
}
Now you've ended up with making sure that there can be only one ActiveContext instance per thread. Which ends you up in all kinds of weird thread singleton mess.
In fact I numerously tried to implement a clean and sane mapping from OpenGL state and objects into a set of C++ classes, but there are always cases where is simply doesn't work out or ends up in horrible code mess.
IMHO it's far better to not try mapping the OpenGL API into a set of C++ classes (it can't be done sanely), but instead use the regular OpenGL API from specialized classes. Any OpenGL context management is so dependent in the program in questions, that it must be tailored specifically to said program.
Wrapping OpenGL and an OpenGL object model are two different concepts. OpenGL entities can easily be made into objects to wrap their functionality and indeed if you want to write a renderer that can be instantiated with, say, either OpenGL or D3D, this is a strict necessity.
I have classes like this:
class Device
class State
class Buffer
class BufferUniform
class BufferVertices
class BufferIndices
class BufferArray
class Texture
class Texture1d
class Texture2d
class Texture3d
class TextureCubeMap
class TextureArray
class TextureRender
class TextureFrame
class Shader
class ShaderPixel
class ShaderVertex
class ShaderGeometry
class ShaderEvaluator
class ShaderTessellator
class ShaderProgram
class ShaderGenerator
class ShaderGeneratorParser
class ShaderGeneratorNode
class ShaderGeneratorCondition
... and either a D3D or an OpenGL version of each. Renderer<...> is instantiated with one set or the other at compile-time, depending on whether I want D3D or OpenGL to do the work.
Is there a well-known C++ wrapper using C++11 facilities for OpenGL? and if not,
No. There have been some attempts at it.
Is something like this planned by anyone well-known (which especially means the Khronos)?
The Khronos ARB doesn't really try to communicate directly with us about upcoming stuff. However, I highly doubt that they care about this sort of thing.
As for anyone else, again, there are some independent projects out there. But generally speaking, people who use OpenGL aren't that interested in doing this sort of thing.
The basic facts are these: OpenGL objects are directly associated with some global concept. Namely, the OpenGL context. Those objects can only be manipulated when the context they exist within (since objects can be shared between contexts) are active.
Therefore, any C++ object-oriented system must decide how fault-tolerant it wants to be. That is, what kinds of assurances that it wants to provide. If you call a function that operates on an object, how certain will you be that this call succeeds?
Here's a list of the levels of assurances that could reasonably be provided:
Completely Anal
In this case, you ensure that every function call either succeeds or properly detects an erroneous condition and fails properly.
In order to pull this off, you need an explicit OpenGL context object. Every OpenGL object must be associated with a share group among contexts (or a specific context itself, if an object type is not shareable).
All object member functions will have to take a context object, which must be the context to which they belong or a member of the share group for that context. There would have to be a per-thread cache of the context, so that they can check to see if the current context is the one they were given, and make it current if it is not.
When a context is destroyed, every object that relied on that context's existence must instantly become non-functional. Thus, every such object needs to have access to some tag (such as via a std::weak_ptr) to let them know that all of their function calls will fail.
If the objects are going to be properly RAII'd, then each object must be able to ensure that a context that they can be destroyed in (ie: glDelete* function) is current. And if it isn't, they need to make one current. So basically, every object needs to hold a reference to a valid context or otherwise needs to be able to create one.
On a personal note, I find this all to be painfully silly. No API is this fault tolerant, nor does it need to be. There's a lot of pointless babysitting and sharing of information. C++ is not a safe language, so it shouldn't waste good memory and/or performance just to provide you this level of safety.
Sane
Here, we get rid of the context-based safety checks. It is up to you the user to make sure that the proper contexts are current before trying to use any object in any way. This is just as true of C++. The main feature of this API is just being nicer than the raw C API.
The OpenGL objects would be RAII style, but they would also have a "dispose" function, which can be called if you want them to clear themselves without deleting their corresponding objects. This is useful if you're shutting down a context and don't want to have to run through and destruct all of the objects.
This system would basically assume that you're wanting pure Direct State Access for these classes. So none of the modifying member functions actually bind the object to the context. They can achieve that in one of several ways:
Use EXT_DSA or the equivalent, where available.
If EXT_DSA or equivalent is not available, store the modified state and send the modifications the next time this object is bound.
Or just bind it, make the modification, and unbind it.
Certain kinds of modifications can't use #2. For example, glBufferData, glBufferSubData and glTexSubImage*D calls. The user really expects them to happen now. These functions should be named in such a way that they are distinguishable from guaranteed non-binding functions.
Any such binding functions should make no effort to restore the previous bound state of the object.
Permissive
Basically, there's a 1:1 correspondence between C++ member functions and C functions. Sure, you'll use C++ operator overloading and such to reduce the needless variations of functions. But when it comes right down to it, you're pretty much writing your C++ code the way you did your C code.
Objects may employ RAII, but they won't provide any real convenience beyond that. Member functions will either bind the object themselves or expect you to have bound them. Or they will use DSA and fail if DSA isn't available.
Why bother?
At the end of the day, there's really nothing much to gain from having a C++ interface to OpenGL. Sure, you get RAII. Well, you can get RAII just fine by using a std::unique_ptr with a special deleter functor (yes, really, this is very possible). But beyond some slight convenience with the API, what real expressive power do you gain that you did not have before?
If you're serious about using OpenGL to develop an application, you're probably going to build a rendering system that, relative to the rest of your code, abstracts OpenGL's concepts away. So nobody would see your fancy C++ interface besides your renderer. And your renderer could just as easily use OpenGL's C API. Why build your renderer off of an abstraction if it buys you pretty much nothing.
And if you're just toying around with OpenGL... what does it matter? Just use the interface you have.