我可以在运行时基于另一个函数创建一个函数吗?

| 我正在使用Microsoft的Detours挂钩API,例如,我可以更改
MessageBoxA
时的情况 以这种方式被调用:
  int (WINAPI* pMessageBoxA)(HWND, LPCTSTR, LPCTSTR, UINT) = MessageBoxA;

  int WINAPI MyMessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
  {
      printf(\"A function is called here!\\n\");
      return pMessageBoxA(hWnd, lpText, lpCaption, uType);  // call the regular MessageBoxA
  }

  DetourTransactionBegin();
  DetourUpdateThread(GetCurrentThread());
  DetourAttach(&(PVOID&)pMessageBoxA, MyMessageBoxA); 
因此,当您呼叫
MessageBoxA
时,您实际上是在呼叫
MyMessageBoxA
。 现在,我想编写一个函数
Hook()
,它将在运行时执行上面的代码。例如,如果我将函数指针
MessageBoxA
传递给该函数,它将完全执行上面的代码。 当然,我也可以将其他函数指针传递给它。 然后有一个问题,当我在
Hook
中获得函数指针时,如何定义一个具有与给定函数相同的返回值和参数的函数(在本例中为
MessageBoxA
int WINAPI MyMessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
),然后填充该函数的函数身体?     
已邀请:
在C ++中,函数不是一流的对象,这意味着它们不能在运行时创建。 但是,您可以使用函数指针数组,每个指针指向一个已定义的函数,并在运行时根据某些条件选择适当的函数指针,然后调用它。看起来您已经在代码段中使用了功能指针。     
这并非完全正确。您可以轻松地存储(成员)函数引用,因此可以让一个函数调用另一个函数(在运行时确定)。 您也可以使用
functor
,它是struct / class的olverloading()运算符。然后,可以使用类的状态来记住要调用的实际函数。函子的示例: STL有一个
<functional>
头,其中包含许多有用的实用程序,以使处理(成员)函数引用“更容易”。来自cplusplus.com的随机示例:
// mem_fun example
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int main () 
{
  vector <string*> numbers;

  // populate vector of pointers:
  numbers.push_back ( new string (\"one\") );
  numbers.push_back ( new string (\"two\") );
  numbers.push_back ( new string (\"three\") );
  numbers.push_back ( new string (\"four\") );
  numbers.push_back ( new string (\"five\") );

  vector <int> lengths ( numbers.size() );

  transform (numbers.begin(), numbers.end(), lengths.begin(), mem_fun(&string::length));

  for (int i=0; i<5; i++) {
      cout << *numbers[i] << \" has \" << lengths[i] << \" letters.\\n\";
  }
  return 0;
}
c ++ 0x具有许多漂亮的新功能(包括\'auto \'类型推断和lambda表达式),这将使许多操作变得更加容易     

要回复问题请先登录注册