简体   繁体   English

使用函数指针变量的地址将函数指针分配给函数

[英]Assign function pointer to a function using the address of function pointer variable

I have a function pointer defined like below: 我有一个定义如下的函数指针:

typedef void (*FPT)(void);
FPT Fp;

The pointer variable "Fp" is located at address 0x1234 I have my function defined like below: 指针变量“ Fp”位于地址0x1234,我的函数定义如下:

void myfunc (void)
{
    return;
}

I do not have access to the symbol name "Fp" but I know its address (0x1234). 我无权访问符号名称“ Fp”,但我知道它的地址(0x1234)。 Now how do I assign the address of myfunc() to "Fp" ?? 现在如何将myfunc()的地址分配给“ Fp”?

This should do what you want. 这应该做您想要的。

FPT *fpt_pointer = (FPT *)0x1234;

*fpt_pointer = myfunc;

But note that it's very bad practice to have hard coded addresses like this. 但是请注意,拥有这样的硬编码地址是非常不好的做法。 I don't know whether you really intend to do that (don't!) or whether you are just describing it that way to simplify the question. 我不知道您是否真的打算这样做(不要!),或者您是否只是以简化问题的方式描述它。 It is very likely to break the next time you run the program (even without a re-compile due to Address Space Layout Randomisation). 下次您运行该程序时很可能会中断(即使由于地址空间布局随机化而无需重新编译)。

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

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