title: C++: Dynamic virtual function call
body: <p>I'm searching for a solution to call virtual function dynamicly. This means to support function calls with offsets and dynamic types at runtime.</p>
  
  <p>I'm working on a plugin for a game (Counter-Strike: Source, if you know it). The plugin interface isn't likely and so you cannot extend as much as most people want. To realize a better way to communicate and manipulate the game, I support calling virtual functions. For example, the CCSPlayer class has those methods:</p>
  
  <pre><code>Offset    Name
  ...
  201       CCSPlayer::Ignite()
  ...
  205       CCSPlayer::CommitSuicide(bool Blah)
  ...
  250       CCSPlayer::SomeFunctionWith2Params(int A1, float A2)
  </code></pre>
  
  <p>Passing these offsets and the pointer to the instance of this class to my current function (see below), I can call this functions:</p>
  
  <pre><code>CBasePlayer *pPlayer = Players.Find("mike");
  bool bResult = Call2&lt;bool, int, float&gt;(210 /* offset */, pPlayer, 20, 50.0f);
  </code></pre>
  
  <p>I do this to call virtual functions I cannot call through the normal routine because the compiler doesn't knows the structure of the derived CCSPlayer class.</p>
  
  <p>And now I want to add a scripting language with dynamic virtual function calls. That means, the scripters can set the amount of params, and of what type they are. Then passing the this-pointer and the offset to the function, to finally execute it. This is my real questions.</p>
  
  <p>Currently I can only hardcode those by using templates and creating a function for every amount of params. Example:</p>
  
  <pre><code>template&lt;typename T, typename A, typename B&gt; T Call2(int iOffset, void *pThis, A arg1, B arg2)
  {
      void **pVTable = *(void***)pThis;
      void *pPointer = pVTable[_iOffset]; 
  
      union
      {
          T (CVCallEmpty::*pCall)(A, B);
          void *pAddress;
      } Data;
  
      Data.pAddress = pPointer;
  
      return (reinterpret_cast&lt;CVCallEmpty*&gt;(*(void***)&amp;pThis)-&gt;*Data.pCall)(arg1, arg2);
  }
  </code></pre>
  
  <p>Now, is there any possibility to support dynamic calls?</p>