Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I pass a C# delegate function to a Managed C++ .Dll?

Tags:

c#

.net

interop

I have this delegate in C#.

public delegate string ACSharpDelegate(string message);

How would I go about creating a Managed C++ .dll that will accept this delegate as a parameter so the C++ .dll can call it?

like image 773
David Basarab Avatar asked Aug 14 '09 17:08

David Basarab


1 Answers

You'll 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 (references CSLibrary):

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 (references CSLibrary and CPPLibrary):

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 ();
    }
  }
}
like image 113
cedrou Avatar answered Oct 17 '22 21:10

cedrou