How to pass C # delegate function to managed C ++. Dll?

I have this delegate in C #.

public delegate string ACSharpDelegate(string message);

How do I start creating a managed C ++. Dll that takes this delegate as a parameter, so C ++. Dll can call it?

+5
source share
1 answer

You will need at least 3 assemblies to avoid circular references.

C # library:

  namespace CSLibrary
  {
    public class CSClass
    {
      public delegate string ACSharpDelegate (string message);

      public string Hello (string message)
      {
        return string.Format("Hello {0}", message);
      }
    }
  }

C ++ / CLI library (CSLibrary links):

using namespace System;

namespace CPPLibrary {

  public ref class CPPClass
  {
  public:
    String^ UseDelegate( CSLibrary::CSClass::ACSharpDelegate^ dlg )
    {
      String^ dlgReturn = dlg("World");
      return String::Format("{0} !", dlgReturn);
    }
  };
}

C # program (CSLibrary and CPPLibrary links):

namespace ConsoleApplication
{
  class Program
  {
    static void Main (string [] args)
    {
      CSLibrary.CSClass a = new CSLibrary.CSClass ();
      CSLibrary.CSClass.ACSharpDelegate dlg = new CSLibrary.CSClass.ACSharpDelegate (a.Hello);

      CPPLibrary.CPPClass b = new CPPLibrary.CPPClass ();
      String result = b.UseDelegate (dlg);

      Console.WriteLine (result);
      Console.Read ();
    }
  }
}
+6
source

All Articles