c - 添加到函数指针,以获得指向另一个函数的指针?

标签 c ruby function-pointers addition

我一直在摆弄函数指针,我有两个特定的函数打印到控制台;结果说它们是 8 个字节,如下所示:

Function Pointer Addresses:
rb_gc_start addr: 0x6ea81360
rb_gc_mark  addr: 0x6ea81368

我能否简单地得到一个指向第一个函数的指针,向该指针加 8,然后得到一个指向第二个函数的指针?

背景:Ruby 源码中有两个函数,rb_gc_startrb_gc_mark;我正在为一个...困难的程序构建一个库。这个程序嵌入了 Ruby,但没有嵌入 Ruby C API(它禁止加载 Ruby 扩展,或 *.so 文件)。我几乎重新创建了环境,我可以直接获取 rb_gc_start 的地址,但是 rb_gc_mark 不是那么容易暴露的,我需要一个指向它的指针来处理所有事情正确工作。

例如:

unsigned long (*rb_gc_start)(void);
void (*rb_gc_mark)(unsigned long);

void my_method(void) {
    rb_gc_start = get_method(rb_mGC, "start"); // 0x6ea81360;
    rb_gc_mark = rb_gc_start + 8; // Does this work?
}

我很可能在这里看起来很傻,但任何有关获得第二个功能的帮助都是最有帮助的。

最佳答案

如果函数指针不在同一个函数指针数组中,则不能这样做。指针和整数值的加法运算符仅对数组中的指针有效。单个对象被视为具有一个元素的数组。

还要考虑到根据 C 标准(6.2.5 类型)

28 A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

和(6.3.2.3 指针)

8 A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.

关于c - 添加到函数指针,以获得指向另一个函数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27054387/

相关文章:

c - 难以理解递归?

c - 使用数组作为函数参数

c - 有效地附加一个带有零的大数组?

ruby - 如何使用 block /lambda 表达式从 Ruby 数组中删除 n 个相同值的元素?

c++ - std::bind 到非静态成员函数抛出一堆错误

c++ - 有人可以解释参数 void(*pfn)(void*) 吗?

c - 当我在 C 中 malloc 另一个字符串时,字符串发生变化

ruby-on-rails - Rails 部分渲染和设计 Action

c++ 指向非静态成员函数的指针

ruby-on-rails - Rails 和 Mongoid::将字符串转换为数组