title: c++/cli pass (managed) delegate to unmanaged code
body: <p>How do I pass a function pointer from managed C++ (C++/CLI) to an unmanaged method? I read a few articles, like <a href="http://msdn.microsoft.com/en-us/library/ms235575.aspx" rel="noreferrer">this one from MSDN</a>, but it describes two different assemblies, while I want only one.</p>
  
  <p>Here is my code:</p>
  
  <p>1) Header (MyInterop.ManagedCppLib.h):</p>
  
  <pre><code>#pragma once
  
  using namespace System;
  
  namespace MyInterop { namespace ManagedCppLib {
  
      public ref class MyManagedClass
      {
      public:
          void DoSomething();
      };
  }}
  </code></pre>
  
  <p>2) CPP Code (MyInterop.ManagedCppLib.cpp)</p>
  
  <pre><code>#include "stdafx.h"
  #include "MyInterop.ManagedCppLib.h"
  
  #pragma unmanaged
  void UnmanagedMethod(int a, int b, void (*sum)(const int))
  {
      int result = a + b;
      sum(result);
  }
  
  #pragma managed
  void MyInterop::ManagedCppLib::MyManagedClass::DoSomething()
  {
      System::Console::WriteLine("hello from managed C++");
      UnmanagedMethod(3, 7, /* ANY IDEA??? */);
  }
  </code></pre>
  
  <p>I tried creating my managed delegate and then I tried to use <code>Marshal::GetFunctionPointerForDelegate</code> method, but I couldn't compile.</p>