我正在学习如何动态加载DLL,但我不明白的是这一行 数组
typedef void (*FunctionFunc)();
我有几个问题。 若是有人可以回答他们,我将不胜感激。 app
typedef
? void
以后,应该没有函数名称或其余名称吗? 它看起来像一个匿名函数。 因此我如今很困惑; 你能为我澄清一下吗? 函数
#include <stdio.h> #include <math.h> /* To define a new type name with typedef, follow these steps: 1. Write the statement as if a variable of the desired type were being declared. 2. Where the name of the declared variable would normally appear, substitute the new type name. 3. In front of everything, place the keyword typedef. */ // typedef a primitive data type typedef double distance; // typedef struct typedef struct{ int x; int y; } point; //typedef an array typedef point points[100]; points ps = {0}; // ps is an array of 100 point // typedef a function typedef distance (*distanceFun_p)(point,point) ; // TYPE_DEF distanceFun_p TO BE int (*distanceFun_p)(point,point) // prototype a function distance findDistance(point, point); int main(int argc, char const *argv[]) { // delcare a function pointer distanceFun_p func_p; // initialize the function pointer with a function address func_p = findDistance; // initialize two point variables point p1 = {0,0} , p2 = {1,1}; // call the function through the pointer distance d = func_p(p1,p2); printf("the distance is %f\n", d ); return 0; } distance findDistance(point p1, point p2) { distance xdiff = p1.x - p2.x; distance ydiff = p1.y - p2.y; return sqrt( (xdiff * xdiff) + (ydiff * ydiff) ); }
typedef
用于别名类型; 在这种状况下,您要将FunctionFunc
别名为void(*)()
。 学习
确实,语法看起来确实很奇怪,请看如下内容: ui
typedef void (*FunctionFunc) ( ); // ^ ^ ^ // return type type name arguments
不,这只是告诉编译器FunctionFunc
类型将是一个函数指针,它没有定义一个函数指针,以下所示: spa
FunctionFunc x; void doSomething() { printf("Hello there\\n"); } x = &doSomething; x(); //prints "Hello there"
若是没有typedef
字,则在C ++中,声明将声明类型为无参数FunctionFunc
的指针类型的FunctionFunc
变量,并返回void
。 prototype
使用typedef
它将FunctionFunc
定义为该类型的名称。 指针
typedef
是一种将名称与类型相关联的语言构造。
例如,您可使用与原始类型相同的方式来使用它 code
typedef int myinteger; typedef char *mystring; typedef void (*myfunc)();
使用它们像 orm
myinteger i; // is equivalent to int i; mystring s; // is the same as char *s; myfunc f; // compile equally as void (*f)();
如您所见,您能够将typedef名称替换为上面给出的定义。
困难在于在C和C ++中指向函数语法和可读性的指针,而typedef
能够提升此类声明的可读性。 可是,语法是适当的,由于与其余更简单的类型不一样,函数可能具备返回值和参数,所以有时会冗长而复杂的函数指针声明。
使用指向函数数组的指针以及其余一些更间接的方式时,可读性可能开始变得很是棘手。
回答你的三个问题
为何要使用typedef? 简化代码阅读-尤为是指向函数或结构名称的指针。
语法看起来很奇怪(在指向函数声明的指针中) ,至少在开始时,语法并不明显。 使用typedef
声明能够简化阅读
是否建立了函数指针来存储函数的内存地址? 是的,函数指针存储函数的地址。 这与仅简化程序的编写/读取的typedef
构造无关; 编译器只是在编译实际代码以前扩展typedef定义。
例:
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
若是可使用C ++ 11,则可能要使用std::function
和using
关键字。
using FunctionFunc = std::function<void(int arg1, std::string arg2)>;