如何为功能指针分配功能

时间:2017-06-10 01:19:37

标签: c function opengl

我希望能够做到这样的事情:

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

我想创建一些功能类似于实现openGL头的方式,其中声明了函数原型,然后将函数设置为指针。换句话说,我想知道一些openGL头文件如何能够加载openGL函数,并同时拥有函数的原型。

2 个答案:

答案 0 :(得分:1)

函数不是变量;他们不能被分配到。

但是,函数可以隐式转换指向这些函数的指针。函数本身仍然不是变量,但是您可以将该函数指针指定给适合该函数指针的变量。

  

我想知道一些openGL头文件如何能够加载openGL函数,并同时拥有函数的原型。

我不知道你正在谈论哪个特定的标题,但是the loader I created只是函数的实现调用函数指针,传递所有参数并返回其值(如果有的话)。指针在源文件中定义,因此它不在标题本身中。

使用您的示例:

//header
void test();

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

void test()
{
  testPointer();
}

你甚至可以得到幻想和make test load the pointer

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

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

答案 1 :(得分:0)

第一

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;
}

第二名:

(如果您使用的是c ++编译器)

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;

}
相关问题