简体   繁体   English

在C中获取sizeof一个void(*)()函数指针

[英]Get sizeof a void (*)() function pointer in C

To aid with some precise memory allocation that I'm doing in C , I'm trying to get the sizeof a function pointer for a function with return type void that takes no parameters. 为了帮助我在C进行一些精确的内存分配,我试图获得函数指针的sizeof ,函数返回类型为void,不带参数。

However, when I do sizeof (void (*)()) , I generate a compiler warning: 但是,当我执行sizeof (void (*)()) ,我会生成一个编译器警告:

function declaration isn't a prototype [-Wstrict-prototypes]

How do I get the size that I'm looking for? 我如何获得我正在寻找的尺寸?

这是一个旧样式函数定义,它缺少参数列表,所以添加它们:

sizeof( void(*)(void) )

For readability purposes, I recommend declaring a type for the signature of any function you'll want have some pointer to: 出于可读性目的,我建议为任何你想要的函数的签名声明一个类型:

 typedef void my_sigt(void);

then, to declare a pointer to such a function, code: 然后,要声明一个指向这样一个函数的指针,代码:

 my_sigt* funptr;

and to get its size code sizeof(my_sigt*) (or sizeof(funptr) if you have such a variable funptr ) 并获得其大小代码sizeof(my_sigt*) (或sizeof(funptr)如果你有这样一个变量funptr

BTW, I am not sure that the C99 standard guarantees that every function pointer has the same size (or has the same size as some data pointer). 顺便说一下,我不确定C99标准是否保证每个函数指针都具有相同的大小(或者与某些数据指针具有相同的大小)。 But POSIX requires that (in particular, to be able to use dlsym for dynamic linking of such functions). 但是POSIX要求(特别是能够使用dlsym来动态链接这些函数)。

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

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