title: C++/CLI managed class member callback by managed code
body: <p>I am designing a class in C++/CLR that uses a callback function provided by user code.</p>
  
  <p>This works very nicely if the callback function is free ( i.e. not the member of a class ).  It is almost the same as in pure C++.</p>
  
  <p>Here is some sample code that works well:</p>
  
  <pre><code>ref class ClassThatUsesCallback
  {
  public:
      typedef void (*callback_t)( String^ );
      void setCallback( callback_t pfun )
      {
          myCallback = pfun;
      }
      void Run()
      {
          if( myCallback != nullptr ) {
              myCallback("This is a test");
          }
      }
  private:
      callback_t myCallback;
  };
  
  void FreeFunction( String^ s )
  {
      Console::WriteLine( "Free Function Callback " + s );
  }
  
  int main(array&lt;System::String ^&gt; ^args)
  {
     ClassThatUsesCallback^ theClassThatUsesCallback
         = gcnew ClassThatUsesCallback();
      theClassThatUsesCallback-&gt;setCallback( FreeFunction );
      theClassThatUsesCallback-&gt;Run();
  }
  </code></pre>
  
  <p>However, I would like the callbacked function to be a member of a class in the user code ( so it can make use of and change the attributes of the user code class )</p>
  
  <p>The following code does not compile</p>
  
  <pre><code>ref class ClassThatProvidesCallback
  {
  public:
      void MemberFunction( String^ s )
      {
          Console::WriteLine( "Member Function Callback " + s );
      }
      void Run()
      {
          ClassThatUsesCallback^ theClassThatUsesCallback
              = gcnew ClassThatUsesCallback();
          theClassThatUsesCallback-&gt;setCallback( 
              &amp;ClassThatProvidesCallback::MemberFunction );
          theClassThatUsesCallback-&gt;Run();
      }
  
  };
  </code></pre>
  
  <p>I get this error</p>
  
  <pre><code>error C3374: can't take address of 'ClassThatProvidesCallback::MemberFunction'
  unless creating delegate instance
  </code></pre>
  
  <p>When I research this, I find numerous explanations of how to call un-managed code from managed code ( and vice-versa )  I do not need to do this - all the code involved is managed.  So I am hoping that someone can point me to a simple way to this.</p>