改变函数指针的地址值 [英] Changing the address value of a function pointer
问题描述
我在 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 进行 OR,但我猜操作数转换有问题:
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.
你仍然可以这样写:
typedef int (*fptr)(int, int);
functionPtr = (fptr)(((intptr_t) functionPtr) | 1);
您正在寻找的行为是更合理的结果之一,但同样,两种类型转换的行为都是未定义.因此,通过修改后的指针执行函数调用所预期的行为——如果你的程序甚至可以做到那么远——也是未定义的.编译器甚至不需要接受代码.
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屋!