title: x64 asm how to set a function pointer to a _cdecl C function and call it?
body: <p>I'm trying to do something pretty basic in x64 asm:</p>
  
  <ol>
  <li><p>Have an asm function which take a function pointer and sets this in a variable. This function is called from C code.</p></li>
  <li><p>Have another asm function which calls the function pointer if not null, this function pointer is also a C function (as as set by the function in 1).</p></li>
  </ol>
  
  <p>Here is what I have so far for the C side of things:</p>
  
  <pre><code>extern "C" void _asm_set_func_ptr(void* ptr);
  
  void _cdecl c_call_back()
  {
  
  }
  
  void init()
  {
      _asm_set_func_ptr(c_call_back);
  }
  </code></pre>
  
  <p>And the asm side:</p>
  
  <pre><code>.DATA
  
  g_pFuncPtr QWORD 0
  
  .CODE             ;Indicates the start of a code segment.
  
  _asm_set_func_ptr PROC fPtr:QWORD
      mov     [rsp+qword ptr 8], rcx
      mov     rax, [rsp+qword ptr 8]
      mov     g_pFuncPtr, rax
      ret
  _asm_set_func_ptr ENDP 
  
  _asm_func PROC
  
  push RBX
  push RBP
  push RDI
  push RSI
  push RSP
  push R12
  push R13
  push R14
  push R15
  
  CMP g_pFuncPtr, 0
  JE SkipCall
      MOV RAX, [ g_pFuncPtr ];
      CALL RAX;
  SkipCall:
  
  pop RBX
  pop RBP
  pop RDI
  pop RSI
  pop RSP
  pop R12
  pop R13
  pop R14
  pop R15
  ret
  
  _asm_func ENDP 
  </code></pre>
  
  <p>But it seems I damage the stack after calling _asm_set_func_ptr(), also I'm not sure if how I call g_pFuncPtr in _asm_func is correct? What is wrong with my code? I'm building this with VS2013 MASM64.</p>