开发者

function descriptors in c

i'm trying to implement a simple array of function descriptors of type fun_desc

struct fun_desc {
  cha开发者_C百科r *name;
  void (*fun)();
};

i have 2 function f1 and f2 both are of type coolFunct

typedef int (*coolFunct) (unsigned int);

my array is defined as follows

struct fun_desc funArr[]={{"f1", &f1}, {"f2",&f2}};

now i am trying to call a function in the array, i presume i need to cast it to coolFunct because it is of unspecified type (or am i wrong) but the next call doesn't work (no compile or runtime error, just nothing happens) :

((coolFunct)(funArr[0].fun))(1);

as always help is greatly appreciated thanks ...


Use this syntax:

(*funArr[0].fun)();

Also, don't cast, your function types differ and things will crash, try this:

typedef int (*coolFunct) (unsigned int);

struct fun_desc {
  char *name;
  coolFunct fun;
};

(*funArr[0].fun)(1);

EDIT: If you actually want to cast, the syntax for calling is:

((coolFunct)funArr[0].fun)(1);


You need to cast the function pointers when you store them in the struct. Your compiler is supposed to give you a diagnostic for this. It's hard to see how it could be the source of your problems though.

#include <stdio.h>
typedef int (*coolFunct) (unsigned int);
typedef void (*whackFunct)();

int f1(unsigned i) { puts("f1"); return 1; }
int f2(unsigned i) { puts("f2"); return 2; }

struct fun_desc {
  char *name;
  void (*fun)();
};

struct fun_desc funArr[]={{"f1", (whackFunct)&f1}, {"f2", (whackFunct)&f2}};

int main()
{
    printf("function returned %d\n", ((coolFunct)funArr[0].fun)(1));
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜