我的代码中有 3 个函数:
#pragma Code(".my_functions")
int func_A(volatile ulong *from, volatile ulong *to, ulong size) {...}
int func_B(uint32_t *buf_src, int size) {...}
void func_C(int size, uint32_t *buf) {...}
#pragma Code()
在此文件的另一个函数中,我需要计算 func_A
和 func_B
的大小:
int calc_size()
{
// End address of B (== start of C) - Start address of A:
int funcs_size = func_C - func_A; // Here the error
// ...
}
我收到下一个编译错误:
error: 'void (*)(int, uint32_t *)' (aka 'void (*)(int, unsigned int *)') and 'int (*)(volatile ulong *, volatile ulong *, ulong)' (aka 'int (*)(volatile unsigned long *, volatile unsigned long *, unsigned long)') are not pointers to compatible types
注意:我可以通过转换函数指针来解决错误,例如:
int funcs_size = (void*)func_C - (void*)func_A;
但是相同大小的计算对于其他函数(也具有不同类型)来说是完美的。
您知道什么时候可以使用函数指针进行此类计算吗?为什么在这个特定示例中我会收到编译错误?
感谢您的帮助
最佳答案
I need to calculate the size of func_A and func_B:
[...]
// End address of B (== start of C) - Start address of A: int funcs_size = func_C - func_A; // Here the error
C 没有任何函数大小的概念,也没有任何标准方法来计算与此类统计相关的任何内容。
I get the next compilation error:
error: 'void (*)(int, uint32_t *)' (aka 'void (*)(int, unsigned int *)') and 'int (*)(volatile ulong *, volatile ulong *, ulong)' (aka 'int (*)(volatile unsigned long *, volatile unsigned long *, unsigned long)') are not pointers to compatible types
嗯,这就是您的代码的一个问题。不过,我认为这更像是转移注意力。对象指针的指针算术是根据指向类型的大小定义的,因此不为指向不兼容类型的指针定义它。函数指针的类型包含其返回类型以及参数的类型(如果指定),因此即使我们假设函数指针是对象指针,它们的类型也不兼容,因此不允许进行减法操作。
NOTE: I can solve the error by casting the function pointers, e.g.:
int funcs_size = (void*)func_C - (void*)func_A;
这依赖于编译器实现的三个单独的扩展:
- 将函数指针转换为对象指针,
- 计算
void *
类型的指针与 - 计算指向不是同一数组的两个成员的对象的指针或指向紧邻数组末尾的位置的指针之间的差异。
就标准而言,这些都没有定义行为。
But the same size calculation works perfect for another functions (with also different types)
由于我们正在处理语言扩展,因此很难说您的编译器可能接受或不接受什么。不过,我注意到,不同参数类型与不兼容参数类型不同,同样不同的函数类型也不一定不兼容。因此,我推测您的编译器可能会接受指向兼容函数类型的指针的差异操作(作为扩展)。
Do you know when it is Ok to use functions pointer for such calculations
这取决于你所说的“OK”是什么意思。如果您尝试编写符合语言标准的代码,那么永远是不行的。您不能计算函数指针之间的差异。您不能将函数指针转换为对象指针来计算它们之间的差异。
您可以将函数指针转换为整数并计算它们的差,但转换结果是实现定义的,并且不能保证有任何整数类型可以表示转换后的函数指针而不需要数据损失。
无论如何,无论是计算指针差异还是整数差异,该差异的含义都是完全未指定的。即使我们假设由此计算出一个函数的起始地址与另一个函数的起始地址之间的差异,相对于一些公共(public)的线性地址空间,也无法保证函数的排列方式在内存中——与它们的相对顺序无关,与它们的连续性无关,与填充或对齐无关,什么都没有。
关于c - 错误 - <函数声明> 不是指向兼容类型的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55362750/