简体   繁体   English

分配作为参数传入的函数指针

[英]Assign a function pointer passed in as a parameter

Is it possible to pass in a function pointer to a function and have that function assign the function to use? 是否可以将函数指针传递给函数并让该函数分配要使用的函数?

Below is an example of what I mean: 以下是我的意思的示例:

void sub(int *a, int *b, int *c)
{
    *c = *a + *b;
}

void add(int *a, int *b, int *c)
{
    *c = *a - *b;
}

void switch_function(void (*pointer)(int*, int*, int*), int i)
{
    switch(i){
        case 1:
            pointer = &add;
            break;
        case 2:
            pointer = ⊂
            break;
    }
}

int main()
{
    int a;
    int b;
    int c;
    void (*point)(int*, int*, int*);

    switch_function(point, 1); // This should assign a value to `point`
    a = 1;
    b = 1;
    c = 0;
    (*point)(&a, &b, &c);

    return 0;
}

Any help is appreciated. 任何帮助表示赞赏。

You can create a pointer to a function pointer. 您可以创建一个指向函数指针的指针。

Here is the syntax: 语法如下:

void (**pointer)(int*, int*, int*);

After you initialized it, you can then dereference this pointer to set your function pointer: 初始化之后,可以取消引用此指针以设置函数指针:

*pointer = &add;
*pointer = ⊂

So your function would look like this: 因此,您的函数将如下所示:

void switch_function(void (**pointer)(int*, int*, int*), int i)
{
    switch(i) {
        case 1:
            *pointer = &add;
            break;
        case 2:
            *pointer = ⊂
            break;
    }
}

...and you'd call it like this: ...您将这样称呼它:

switch_function(&point, 1);

The syntax is much easier if you use a typedef for your function pointer. 如果将typedef用作函数指针,则语法会容易得多。 Especially if you use a double indirection in your sample. 尤其是在样本中使用双重间接寻址的情况下。

typedef void (*fptr)(int*, int*, int*);

void sub(int *a, int *b, int *c)
{   
    *c = *a - *b;
}

void add(int *a, int *b, int *c)
{   
    *c = *a + *b;
}

void switch_function(fptr *pointer, int i)
{
    switch(i){
        case 1:
            *pointer = &add;
            break;
        case 2:
            *pointer = ⊂
            break;
    }
}

int main()
{
    int a;
    int b;
    int c;
    fptr point;

    switch_function(&point, 1);
    a = 1;
    b = 1;
    c = 0;
    (**point)(&a, &b, &c);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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