glGenBuffers returns 0


I am working on OS X Mountain Lion and Xcode 4.6. I am using the Cocoa APIs to create my windows and handle events. I can’t seem to get a vertex buffer generated for some reason. I use NSLog() to print the value of my buffer, but it comes out as 0. Could someone please assist me? Here is my code, it is inside of a custom NSOpenGLView:

@implementation MyOpenGLView

static const GLfloat g_vertex_buffer_data[] = {
    -1.0f, -1.0f, 0.0f,
    1.0f, -1.0f, 0.0f,
    0.0f,  1.0f, 0.0f,


    NSOpenGLPixelFormatAttribute attrs[] =
        NSOpenGLPFADepthSize, 24,
        // Must specify the 3.2 Core Profile to use OpenGL 3.2
    NSOpenGLPixelFormat *pf = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs] autorelease];
    if (!pf)
        NSLog(@"No OpenGL pixel format");
    NSOpenGLContext *context = [[[NSOpenGLContext alloc]initWithFormat:pf shareContext:nil]autorelease];
    [self setPixelFormat:pf];
    [self setOpenGLContext:context];
    GLuint vertexBuffer;
    glGenBuffers(1, &vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

- (id)initWithFrame:(NSRect)frame
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    return self;

- (void)drawRect:(NSRect)dirtyRect

    glClearColor(0.0, 0.0, 0.0, 1.0);
    NSLog(@"drawRect: is called");


I get a black window like expected with no errors or warning. My vertex buffer object is 0 for some reason.

Not knowing anything about MACs I may tap in the dark, but: Your gl-specific code seems ok, so it has got to be something else. What I notice is that you don’t check for “context” to be non-NULL respectively to be initialized successfully. I’d check that, although I do not know if the black Screen rules this out.

Thanks! Though my context was set up correctly, you led me to think something context-wise was wrong; you were right. Apparently on OS X any OpenGL calls pertaining to setting up OpenGL must go in prepareOpenGL: in the NSOpenGLView subclass. Thanks Again!

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.