用于保存函数指针的整数类型?
Integer type for holding function pointers?
我应该使用哪种标准定义的整数类型来保存指向函数的指针?是否有可以容纳任何函数的类似于 (void*)
的函数类型?
可以肯定它不是[u]intptr_t
,因为标准明确表示它用于指向对象的指针,并且标准明确区分了指向对象的指针和指向函数的指针。
没有指定足以编码函数指针的整数类型。
备选方案:
更改代码以取消对该整数类型的需求。很少真正需要这样的整数类型。
使用数组:unsigned char[sizeof( int (*)(int)) )]
和 union
中的 int (*f)(int))
以允许对指针的整数性进行一些检查。仍然可能存在填充问题。归结为代码想要对这样的整数做什么。
使用uintmax_t
,希望够用。 _Static_assert(sizeof (uintmax_t) >= sizeof (int (*)(int)) );
是合理的预防措施,但不能保证成功。
极限规格
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type. C17dr § 6.3.2.3 6
请注意,即使 [u]intptr_t
对象指针类型也是一种保证,因为它们是可选类型。
It's very certain that it's not [u]intptr_t
这是真的。但是区别只是为了保证一些基本转换的正确性。如果您查看“The C Programming Language”的第 2 版,那么与标准中的当前措辞相比,区别更加微妙。
如果您的目标平台具有操作系统,那么 [u]intptr_t
可能 正是 您想要的,如:
POSIX 指定 dlsym
函数 returns void *
要求结果可以转换为函数指针并可用。
Win32 GetProcAddress
的定义方式是,如果 return 值不为 NULL,它将是对函数有效的有效内存地址 and/or 个对象。
我应该使用哪种标准定义的整数类型来保存指向函数的指针?是否有可以容纳任何函数的类似于 (void*)
的函数类型?
可以肯定它不是[u]intptr_t
,因为标准明确表示它用于指向对象的指针,并且标准明确区分了指向对象的指针和指向函数的指针。
没有指定足以编码函数指针的整数类型。
备选方案:
更改代码以取消对该整数类型的需求。很少真正需要这样的整数类型。
使用数组:
unsigned char[sizeof( int (*)(int)) )]
和union
中的int (*f)(int))
以允许对指针的整数性进行一些检查。仍然可能存在填充问题。归结为代码想要对这样的整数做什么。使用
uintmax_t
,希望够用。_Static_assert(sizeof (uintmax_t) >= sizeof (int (*)(int)) );
是合理的预防措施,但不能保证成功。
极限规格
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type. C17dr § 6.3.2.3 6
请注意,即使 [u]intptr_t
对象指针类型也是一种保证,因为它们是可选类型。
It's very certain that it's not
[u]intptr_t
这是真的。但是区别只是为了保证一些基本转换的正确性。如果您查看“The C Programming Language”的第 2 版,那么与标准中的当前措辞相比,区别更加微妙。
如果您的目标平台具有操作系统,那么 [u]intptr_t
可能 正是 您想要的,如:
POSIX 指定
dlsym
函数 returnsvoid *
要求结果可以转换为函数指针并可用。Win32
GetProcAddress
的定义方式是,如果 return 值不为 NULL,它将是对函数有效的有效内存地址 and/or 个对象。