title: Pin a function pointer
body: <p>I need to pass a managed callback to an unmanaged TCP receiver. Since its a thread that needs to exist for the lifetime of the application, I need to prevent it from getting garbage collected. I have read everywhere that pinning function pointers is not required and the GCHandle.Alloc will do the job of preventing garbage collection.</p>
  
  <p>But is this a given? I have seen that the AppPool hosting this code crashes with an access violation. Why should I not suspect the fact that this error occurs because the function pointer was garbage collected?</p>
  
  <p>This <a href="https://stackoverflow.com/a/3366436/382795">post</a> supports this fact.</p>
  
  <p>Update:
  This seems to have reduced the crashes considerably. Is there a problem with this approach? </p>
  
  <pre><code>typedef void (__cdecl *ProcMessageFunc)(void* param, void* paramBuf, ULONG bufSize);
  FuncDelegate^ fp = gcnew MessageFuncDelegate(this, &amp;Handler); 
  pin_ptr&lt;MessageFuncDelegate^&gt; pinnedFunctionPointer = &amp;fp; 
  ret = Receiver ((ProcMessageFunc)pinnedFunctionPointer);
  </code></pre>