小编aki*_*ata的帖子

函数指针通过继承的 C 结构转换为函数

我正在寻找答案,如果示例函数转换和调用在 C 中有效(如果没有任何示例,如何获得类似的行为会很好)。

例子:

#include <stdio.h>
#include <stdint.h>

typedef struct {
    uint32_t a;
} parent_t;

typedef struct {
    parent_t parent;
    uint32_t b;
} child_t;


typedef void (*funct_ptr_t)(parent_t* pParent, uint32_t x);

void test_function(child_t* pChild, uint32_t x);

int main()
{ 
    funct_ptr_t func = (funct_ptr_t)test_function;
    funct(NULL, 0U);

    return 0;
}

void test_function(child_t* pChild, uint32_t x) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

@编辑如上所述无效,我还想询问第二种方法

typedef void (*funct_ptr_t)(void* pChild, uint32_t x);

void test_function(child_t* pChild, uint32_t x);

int main()
{ 
    funct_ptr_t func = (funct_ptr_t)test_function;
    child_t child;
    func(&child, 0U); …
Run Code Online (Sandbox Code Playgroud)

c language-lawyer

5
推荐指数
1
解决办法
71
查看次数

C 中继承结构的向上转型和向下转型

我想知道所提供的示例在 C 中是否安全(无 UB):

typedef struct {
    uint32_t a;
} parent_t;

typedef struct {
    parent_t parent;
    uint32_t b;
} child_t;

typedef struct {
    uint32_t x;
} unrelated_t;

void test_function(parent_t* pParent) {
    ((child_t*)pParent)->b = 5U; // downcast is valid only if relation chain is valid
}

int main()
{
    child_t child;
    unrelated_t ub;
    test_function((parent_t*)&child); // valid upcast?
    test_function((parent_t*)&ub); // probably UB?

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

由于显式转换,没有保证和良好的类型检查,但只要传递正确的参数,这应该可以正常工作吗?

c language-lawyer

1
推荐指数
1
解决办法
340
查看次数

标签 统计

c ×2

language-lawyer ×2