title: Passing a C# callback function through Interop/pinvoke
body: <p>I am writing a C# application which uses Interop services to access functions in a native C++ DLL.  I am already using about 10 different functions which are working.</p>
  
  <p>Now I am not sure how to handle passing a callback as a parameter so that the DLL can call my code.</p>
  
  <p>Here is the function prototype of the DLL:</p>
  
  <pre><code>typedef void (WINAPI * lpfnFunc)(const char *arg1, const char *arg2)
  </code></pre>
  
  <p>And the function that allows me to pass the above type:</p>
  
  <pre><code>int WINAPI SetFunc(lpfnFunc f)
  </code></pre>
  
  <p>Here is my C# code for the delegate and function definitions:</p>
  
  <pre><code>public delegate void Func(string arg1, string arg2);
  
  public static void MyFunc(string arg1, string arg2)
  </code></pre>
  
  <p>Here is my C# code for the SetFunc Interop function:</p>
  
  <pre><code>[DllImport("lib.dll", CharSet = CharSet.Ansi)]
  public static extern int SetFunc(Func lpfn);
  </code></pre>
  
  <p>And finally here is the code where I call the SetFunc function and pass it my callback:</p>
  
  <pre><code>SetFunc(new Func(MyFunc));
  </code></pre>
  
  <p>Unfortunately my function is not being called when it should be.  The return value of the SetFunc function is returning the error code for a Success, so either it's not calling my function or it's not working because my code is wrong.</p>