Reading the color of a single pixel with glReadPixels

I have to write a C function that finds the color of a single pixel at (x,y). I’m using gcc from the Cygwin distribution running on WinXP with 32-bit color, if that matters. I’ve read the documentation of glReadPixels and the best I’ve come up with is:

void getPixel(int x, int y, int* color) {

I must be really stupid about something, because this doesn’t work. Any suggestions? Larry

I would do this:

GLubyte rgba[4];

void getPixel(int x, int y, GLubyte *color) {
glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, color);

getPixel(x,y, rgba);

Mind that OpenGL’s coordinates are bottom-left origin. If you use this with windows (mouse) coordinates, you need to invert y by doing

getPixel(x, viewportHeight - 1 - y, rgba);

Stating the obvious, you need to have an OpenGL context current.
Make sure your glReadBuffer() points to the right buffer! For double buffered pixelformats, glDrawBuffer and glReadBuffer point to GL_BACK(_LEFT) per default. After SwapBuffers(), consider the backbuffer contents to be undefined if the pixelformatdescriptor has the PFD_SWAP_EXCHANGE flag set, that is, read before the SwapBuffers or read from front after the swap.
Areas which are overlapped by other windows, will return undefined results since they fail the pixel ownership tests.
If your pixelformat has no alpha bits, the above code will always return 1.0 (0xFF) for the alpha channel.
Pixel pack alignment affects the call. The default is 4 which will just work fine here since you write four bytes.

OK, I finally tracked this down to a mistake in
setting up the viewing transformation in the
main program. Mea culpa and thanks for the help
I received.