简体   繁体   中英

How Can I Assign a Function to a Function Pointer

I would like to be able to do something like this:

void test();
void (*testPointer)() = SomethingThatReturnsAFunctionPointer();
test = testPointer;

I would like to make something that functions similarly to the way openGL headers are implemented in which function prototypes are declared, and then the functions are set to a pointer. In other words, I would like to know how some openGL header files are able to both load the openGL functions, and have prototypes of the functions at the same time.

Functions are not variables; they cannot be assigned to.

However, functions can be implicitly converted to pointers to those functions. The function itself still isn't a variable, but you can assign that function pointer to a variable that is suitably typed for that function pointer.

I would like to know how some openGL header files are able to both load the openGL functions, and have prototypes of the functions at the same time.

I don't know which particular header you're talking about, but the loader I created simply has the implementation of the function call the function pointer, passing it all of the parameters and returning its value (if any). The pointer is defined inside a source file, so it's not in the header itself.

Using your example:

//header
void test();

//source file
void (*testPointer)();

void test()
{
  testPointer();
}

You can even get fancy and make test load the pointer :

//source file
void (*testPointer)() == NULL;

void test()
{
  if(!testPointer)
  {
    testPointer = SomethingThatReturnsAFunctionPointer();
  }
  testPointer();
}

1st:

int aplusb(int a, int b){return a + b;}
int aminusb(int a, int b){return a - b;}

int (*func)(int a, int b) = aplusb;

int some_func_caller ( int A, int B, int (*func)(int a, int b)){
   return func(A, B);
}

 int main(){
    int a_ =10, b_ = 7;
    int res1 = func(a_, b_);
    int res2 = somefunc_caller(a_, b_, aminusb); 
    return 0;
}

2nd:

(if you re using c++ compiler)

typedef int MyFuncionType(int a, int b);
typedef int (*MyFuncionType2)(int a, int b);

int aplusb(int a, int b){return a + b;}
int aminusb(int a, int b){return a - b;}

int some_function_caller1(int a, int b, MyfunctionType fc){return fc(a,b);}
int some_function_caller2(int a, int b, MyfunctionType2 fc){return fc(a,b);}

int main(){
   int a_ = 10, b_ = 7;
   MyFunctionType *func1 = aminusb, *func2 = nullptr;
   MyFunctionType2 func3 = aplusb, func4 = nullptr;

  int res1 = func1(a_, b_);
  int res2 = func3(a_, b_);

  int res3 = some_function_caller1(a_, b_, aplusb);
  int res4 = some_function_caller2(a_, b_, aminusb);

  return 0;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM