更改函数指针的地址值 [英] Changing the address value of a function pointer

查看:107
本文介绍了更改函数指针的地址值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C语言中有以下代码:

I have the following code in C:

int addInt(int n, int m) {
    return n + m;
}

int (*functionPtr)(int, int);

functionPtr = &addInt;

functionPtr 是一个函数指针,它指向函数 addInt 的特定地址.我想更改其值的1位,但我不知道如何更改.

functionPtr is a function pointer and it points to the specific address of the function addInt. I want to change 1 bit of its value, but I can't figure it out how.

假设 functionPtr 指向最后一条语句后的 0xABC0 (假定为16位地址).我想将其值更改为 0xABC1 .我尝试将值与0x1进行或"运算,但我猜操作数转换出了点问题:

Let's say functionPtr points to 0xABC0 (assuming a 16-bit address) after the last statement. I want to change its value to 0xABC1. I tried to OR the value with 0x1, but I guess that something is wrong with the operand conversion:

functionPtr = &addInt | 0x00000001; // addresses are of 32 bits

我知道弄乱指针是有风险的,但是我必须更改地址的LSB才能进入ARM Cortex-M4 MCU的Thumb状态.

I know that messing around with pointers is risky, but I have to change the LSB of the address in order to enter into the Thumb state of an ARM Cortex-M4 MCU.

推荐答案

要通过算术运算来修改指针的值,您需要将其转换为整数类型,执行该操作,然后再将其转换回去. C没有定义将函数指针转换为其他函数指针以外的行为的方法,因此,没有定义的方法可以实现这一点.

To modify the value of a pointer via arithmetic operations, you would need to convert it to an integer type, perform the operation, and then convert it back. C does not define behavior for converting a function pointer to anything other than another function pointer, however, so there is no defined way to do that.

尽管如此,您仍然可以这样写:

You might nevertheless write this:

typedef int (*fptr)(int, int);

functionPtr = (fptr)(((intptr_t) functionPtr) | 1);

您正在寻找的行为是更合理的结果之一,但同样,两个强制类型转换的行为都是 undefined .因此,通过修改后的指针执行功能调用所期望的行为-如果您的程序甚至可以达到目标-也是不确定的.即使接受代码也不需要编译器.

The behavior you are looking for is one of the more plausible results, but again, the behavior of both casts is undefined. Therefore the behavior to be expected from performing a function call via the modified pointer -- if your program can even get that far -- is also undefined. The compiler is not required even to accept the code.

这篇关于更改函数指针的地址值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆