简体   繁体   English

C-要求加入非结构或联合的成员

[英]C - request for member in something not a structure or union

Long story short I am trying to access a function inside one of my structures. 长话短说,我正在尝试访问我的结构之一中的函数。 Below is a simplified verson of my code: 下面是我的代码的简化版本:

#include <stdio.h>

typedef struct
{
    void *data;
} A_t;

typedef struct
{
    void (*function)(void);
} B_t;

void myfunction(void)
{
    fprintf(stdout, "Hello world.\n");
}

int main(int p_argc, char *p_argv[])
{
    A_t A;
    B_t B;

    B.function = myfunction;
    A.data = &B;
    A.data.function();

    return 0;
}

When trying to compile this code I get: 当尝试编译此代码时,我得到:

main.c:24:11: error: request for member ‘function’ in something not a structure or union
 A.data.function();

Could somebody explain me how to properly access this function via the A-structure? 有人可以解释我如何通过A结构正确访问此功能吗?

Thanks 谢谢

data is of type void *, you need to type cast before de-referencing. 数据的类型为void *,则需要在取消引用之前键入强制类型转换。

#include <stdio.h>

typedef struct
{
    void *data;
} A_t;

typedef struct
{
    void (*function)(void);
} B_t;

void myfunction(void)
{
    fprintf(stdout, "Hello world.\n");
}

int main(int p_argc, char *p_argv[])
{
    A_t A;
    B_t B;

    B.function = myfunction;
    A.data = &B;
    ((B_t*)(A.data))->function();

    return 0;
}

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

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