Function Pointer

• 11-04-2003
curlious
Function Pointer
I have a function in my code that I want to return a pointer to a function. The result would then invoke the returned function. How would I set this up? Here is the code for the function that returns one of two pointer to another function.
Code:

```USHORT * getPixelFormat() {         DDPIXELFORMAT ddpixel;         //clear out structure         memset(&ddpixel, 0, sizeof(ddpixel));         //set length         ddpixel.dwSize = sizeof(ddpixel);         //use primary surface interface to get pixel format         lppdsprimary->GetPixelFormat(&ddpixel);         //determine function corresponding to pixel format         BOOL RGB = (ddpixel.dwFlags & DDPF_RGB);                 // test for mode 5.5.5         if (RGB & (ddpixel.dwRGBBitCount==15))                    return RGB16BIT555;                          if (RGB & (ddpixel.dwRGBBitCount==16))                 return RGB16BIT565;         return NULL; }```
Here is more of the code I have tried.
Code:

```//Prototypes USHORT * getPixelFormat(); USHORT RGB16BIT555(int r, int g, int b); USHORT RGB16BIT565(int r, int g, int b); USHORT (*pfnColor)(int,int,int);                        // pointer to RGBcolor function . . .         // Determine color function based on pixel format                 pfnColor = getPixelFormat(); . . . void Plot_Pixel(int x, int y, int red, int green, int blue, USHORT * video_buffer, int lpitch) {         USHORT pixel = (*pfnColor)(red,green,blue);         video_buffer[x+y*(lpitch>>1)]=pixel; }```
• 11-04-2003
Salem
If you want to keep your sanity, make a typedef for the type of the function you want to return a pointer to.

```#include <stdio.h> typedef void (*fp)(void); void foo ( void ) {     printf( "This is foo\n" ); } void bar ( void ) {     printf( "This is bar\n" ); } fp chooser ( int which ) {     if ( which ) {         return foo;     } else {         return bar;     } } int main ( void ) {     fp one = chooser(0);  // grab a function     fp two = chooser(1);     one();  // and call it     two();     // combined     chooser(0)();     return 0; }```