简体   繁体   English

常量结构内的函数指针

[英]Function pointer inside a constant struct

I'm using a driver written by someone else. 我正在使用别人编写的驱动程序。 To access the driver functions, I have to use a function access struct like the one below: (defined in a header file, say, driver.h ) 要访问驱动程序函数,我必须使用如下函数访问结构:(在头文件中定义,例如driver.h

typedef struct _driver {
  void (*init) (void);           // init is supposed to point to _init
} const driver;                  // problem here with **const**

----------------------------------------------------------------------

void _init (void) {              // defined in another file, say, driver.c
  // init code 
}

How can I make init point to _init ? 如何使init指向_init

The following code works if the driver is not const : 如果驱动程序不是const,则以下代码有效:

driver dr;
dr.init = &_init;                // modifying directly 
((driver*)(&dr))->init = &_init; // modifying through a pointer

According to the documentation, the driver is supposed to be used as follows: 根据文档,应按以下方式使用驱动程序:

driver dr;
driver *pdr = &dr;
pdr->init();  

In order for this code to work, dr.init must point _init , but I can't find it anywhere in the code. 为了使此代码起作用, dr.init必须指向_init ,但是我在代码的任何地方都找不到它。 Any input is greatly appreciated. 任何输入,不胜感激。

Best regards, 最好的祝福,

Sergey 谢尔盖

使用初始化程序 ,例如

driver dr = { _init };

rmartinjak's answer is right, but if you have gcc extensions enabled or using C99 and above, you can use designated initializers . rmartinjak的答案是正确的,但是如果启用了gcc扩展或使用C99及更高版本,则可以使用指定的初始化程序 Since your driver struct will probably have more members, this way will probably end up being cleaner looking. 由于您的驱动程序结构可能会有更多的成员,因此这种方式可能最终看起来更干净。

driver dr = {
    .init = _init,
    /* .member = value, */
};

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

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