typedef函数指针?

2022-01-30 00:00:00 pointers c c++ typedef

我正在学习如何动态加载 DLL,但我不明白的是这一行

I'm learning how to dynamically load DLL's but what I don't understand is this line

typedef void (*FunctionFunc)();

我有几个问题.如果有人能够回答他们,我将不胜感激.

I have a few questions. If someone is able to answer them I would be grateful.

  1. 为什么要使用typedef?
  2. 语法看起来很奇怪;在 void 之后不应该有函数名什么的吗?它看起来像一个匿名函数.
  3. 是否创建了函数指针来存储函数的内存地址?
  1. Why is typedef used?
  2. The syntax looks odd; after void should there not be a function name or something? It looks like an anonymous function.
  3. Is a function pointer created to store the memory address of a function?

所以我现在很困惑;你能帮我澄清一下吗?

So I'm confused at the moment; can you clarify things for me?

推荐答案

typedef 是一种将名称与类型相关联的语言结构.
例如,您可以像使用原始类型一样使用它

typedef is a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance

typedef int myinteger;
typedef char *mystring;
typedef void (*myfunc)();

像这样使用它们

myinteger i;   // is equivalent to    int i;
mystring s;    // is the same as      char *s;
myfunc f;      // compile equally as  void (*f)();

如您所见,您可以将 typedefed 名称替换为上面给出的定义.

As you can see, you could just replace the typedefed name with its definition given above.

难点在于C和C++中指向函数的语法和可读性,而typedef可以提高此类声明的可读性.但是,语法是合适的,因为函数 - 与其他更简单的类型不同 - 可能有返回值和参数,因此有时需要冗长而复杂的函数指针声明.

The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.

对于指向函数数组的指针以及其他一些更间接的风格,可读性可能开始变得非常棘手.

The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.

回答你的三个问题

  • 为什么要使用 typedef?为了便于阅读代码 - 特别是对于指向函数或结构名称的指针.

  • Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.

语法看起来很奇怪(在函数声明的指针中)这种语法读起来并不明显,至少在开始时是这样.使用 typedef 声明来简化阅读

The syntax looks odd (in the pointer to function declaration) That syntax is not obvious to read, at least when beginning. Using a typedef declaration instead eases the reading

是否创建了函数指针来存储函数的内存地址?是的,函数指针存储函数的地址.这与 typedef 结构无关,它只会简化程序的写入/读取;编译器只是在编译实际代码之前扩展 typedef 定义.

Is a function pointer created to store the memory address of a function? Yes, a function pointer stores the address of a function. This has nothing to do with the typedef construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.

例子:

typedef int (*t_somefunc)(int,int);

int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

相关文章