用内存地址声明函数

时间:2016-09-28 06:44:30

标签: c++ c++14 memory-address

我正在尝试通过其内存地址调用函数。

我做过类似的事情:

int GetNewValue(int args)
{
  return args * 2;
}

int main()
{
  /*
      Function address: 0x22feac
  */

  int(*GetVal)(int) = 0x22feac; // instead of '&GetNewValue'
}

但是在编译时,我收到以下错误:

  

[错误]无效转换为intint (*)(int) [-fpermissive]

如何从地址调用方法?

(注意上面的例子使用常量来简化,但在我的实际代码中,我从DLL注入中挂钩函数。)

1 个答案:

答案 0 :(得分:1)

地址0x22feac看起来像普通代码地址空间中的任何地址。但这取决于您的环境。在源代码中使用由数字文字指定的地址通常是个坏主意。

但是可能有一个从外部获得的地址,例如来自Windows函数GetProcAddress。如果您确定自己确实知道自己在做什么,那么可以将这样的值赋给函数指针:

intptr_t functionAddress = 0x22feac;
auto GetVal = reinterpret_cast<int(*)(int)>(functionAddress);

auto可让您关注“不要自己重复”#34;图案。