繁体   English   中英

Function 指针指向不同数量的 arguments 的函数

[英]Function pointer pointing to functions with different number of arguments

如何处理将函数分配给一个 function 指针,每个指针具有不同数量的参数? 问题是参数的数量和类型不同。 可以的话举个例子。

Function 指针可以以与其他指针相同的方式进行转换。 您将拥有一个通用的 function 指针(类似于存储类型的void * ),并使用它来保存/传递 function 的地址。 在调用 function 之前,您需要将其转换为正确的类型。

这是一个工作示例:

#include <stdio.h>

typedef void (*generic_t)(void);
typedef int  (*type2_t)(int);
typedef int  (*type3_t)(int, char *s);


void test1(void) {
    printf("Test 1\n");
}

int test2(int i) {
    printf("Test 2 %i\n",i);
    return i;
}

int test3(int i, char *s) {
    printf("Test 3 %i, %s\n", i, s);
    return i++;
}

int main(void) {
    generic_t f1, f2, f3;
    f1 = &test1;
    f2 = (generic_t)&test2;
    f3 = (generic_t)&test3;

    f1();
    int i = ((type2_t)f2)(10);
    i = ((type3_t)f3)(20,"This is test");
}

此外,您需要实现一种机制来识别指针指向的 function 的类型。 一种方法是使用包含struct和类型enum的结构。

另一种可能性是创建不同 function 指针类型的联合:

union funptr {
    void (*v)();
    void (*vi)(int);
    void (*vs)(char *);
    int  (*i)();
    int  (*ii)(int);
    int  (*iii)(int, int);
    int  (*is)(char *);
};

您可以使用 void 指针来传递对inout参数的引用。 您可以将多个参数和返回值包装在结构中。 返回值可能返回状态。

有时它用于低级设备驱动程序。

typedef int func(void *, void *);

func *fptr;

struct s1 
{
    int i;
    char *s;
};

int test1(void *in, void *out) 
{
    printf("Test 1\n");
    return 0;
}

int test2(void *in, void *out) 
{
    int *i = in;
    printf("Test 2 %i\n", *i);
    return *i;
}

int test3(void *in, void *out) 
{
    struct s1 *s = in;
    printf("Test 3 %i, %s\n", s -> i, s -> s);
    return ++s -> i;
}

int main(void) 
{
    fptr = test1;
    fptr(NULL, NULL);
    fptr = test2;
    fptr((int[]){10}, NULL);
    fptr = test3;
    printf("Returned value: %d\n", fptr(&(struct s1){20,"This is test"}, NULL));
}

您必须为需要处理的每个不同签名声明一个新的 function 指针类型。

暂无
暂无

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

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