2
\$\begingroup\$

I'm writing cross-platform (iOS, Android, OSX, Windows) library code that draws its output using OpenGL. I expect my users will often try to call my library's rendering functions without a valid OpenGL context (especially when they are first getting started), so how can I cleanly handle the error?

So far I have tried calling some OpenGL function and then calling glGetError() to see if it failed (and printing my user a helpful error message), but glGetError() segfaults if there is no context:

// Test for OpenGL Context

glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // This line segfaults

if (glGetError() != GL_NO_ERROR)
    printf("You tried to call a rendering function but no OpenGL context was found!");

Is there a way to check for a valid context within OpenGL without getting a segfault?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You can use these vendor specific functions:

  • wglGetCurrentContext() on Windows,
  • aglGetCurrentContext() on OSX,
  • glxGetCurrentContext() on unixoid systems with X and
  • eglGetCurrentContext() on GLES based systems like iOS or Android

They all return NULL (except for eglGetCurrentContext, which returns EGL_NO_CONTEXT) if there is no valid context currently active.

\$\endgroup\$
4
  • \$\begingroup\$ The problem with this is I don't have any control over the context creation/management. Could I assume that these functions will work however my users decide to create their context? \$\endgroup\$ Commented Nov 25, 2013 at 13:36
  • 1
    \$\begingroup\$ No you cannot safely assume that. Depending on what is used to create the context those functions might not even be present. If you don't have control over the context management you can't check the active context directly. But maybe you could make it mandatory for the user to provide a callback that returns whether or not a context is active. \$\endgroup\$
    – kolrabi
    Commented Nov 25, 2013 at 13:54
  • \$\begingroup\$ Ok thanks, that's what I featured looking through the header I found aglGetCurrentContext() in on OSX. It's hard to believe there's no function/macro in the OpenGL API to check current context. Surely, it's just a case of reading one thread-local variable! \$\endgroup\$ Commented Nov 25, 2013 at 14:04
  • 2
    \$\begingroup\$ No, it is implementation-dependent, which is why these functions are in the OS-level implementations and not GL itself. \$\endgroup\$
    – user1430
    Commented Nov 25, 2013 at 16:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .