简体   繁体   English

在C中创建和初始化包含函数指针的结构的正确方法是什么?

[英]What is the right way of creating and initializing a struct containing a function pointer in C?

I have done my reading in structs but everywhere I see different ways of creating them and initializing them. 我已经读完结构,但是到处都可以看到创建和初始化它们的不同方法。 Can you please tell me your opinion on the way I've done it and point out what would you change and why! 能否请您告诉我您对我的工作方式的看法,并指出您将进行哪些更改以及原因?

in the header: 在标题中:

typedef void (*ActionFunc)(void);

typedef struct {
    ActionFunc func;
} MyStruct;

in the C file: 在C文件中:

static MyStruct* my_struct;

void action(){
    /*....*/
}

void my_function(){
    my_struct = &(MyStruct){
        .func = action
    };
}

I don't understand why you've made my_struct into a pointer. 我不明白为什么您my_struct成为指针。

The initialization in my_function() won't work, you're setting my_struct to the address of a compound literal, which won't stick around when my_function exits. my_function()的初始化将不起作用,您将my_struct设置为复合文字的地址,当my_function退出时,该文字不会停留在周围。

Just make my_func a proper global structure (if that's what you need), not a pointer, and change it directly. 只需将my_func为适当的全局结构(如果需要的话)(而不是指针),然后直接更改它即可。

static MyStruct my_struct;

void my_function(void)
{
  my_struct.func = action;
}

You can access the stored function pointer from anywhere ( my_struct is global , after all!) like so: 您可以从任何地方访问存储的函数指针( my_struct毕竟是global !),如下所示:

void random_function(void)
{
  extern struct MyStruct my_struct;

  my_struct.func();
}

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

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