gpt4 book ai didi

c - 常量结构内的函数指针

转载 作者:行者123 更新时间:2023-11-30 17:38:46 24 4
gpt4 key购买 nike

我正在使用别人编写的驱动程序。要访问驱动程序函数,我必须使用如下所示的函数访问结构:(在头文件中定义,例如 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
}

如何让init指向_init

如果驱动程序不是 const,则以下代码有效:

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

根据文档,驱动程序应该按如下方式使用:

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

为了使此代码正常工作,dr.init 必须指向 _init,但我在代码中找不到它。任何意见都将受到高度赞赏。

最诚挚的问候,

谢尔盖

最佳答案

使用初始化程序,例如

driver dr = { _init };

关于c - 常量结构内的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22038159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com