c# - 如何将 C# 委托(delegate)函数传递给托管 C++ .Dll?

标签 c# .net interop

我在 C# 中有这个委托(delegate)。

public delegate string ACSharpDelegate(string message);

我将如何创建一个托管 C++ .dll 来接受这个委托(delegate)作为参数,以便 C++ .dll 可以调用它?

最佳答案

您至少需要 3 个程序集才能避免循环引用。

C# 库:

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

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

C++/CLI 库(引用 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# 程序(引用 CSLibrary 和 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 ();
    }
  }
}

关于c# - 如何将 C# 委托(delegate)函数传递给托管 C++ .Dll?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1279062/

相关文章:

c# - ASP.NET MVC 4 中的 Global.asax.cs 文件采用什么模式?

c# - HttpClient GetAsync 失败

c# - 尝试应用良好的依赖注入(inject)实践时遇到的问题

c# - 寻找 .NET 的命令行参数解析器

c++ - 如何在 C++ 中使用 MATLAB 函数 randn?

c# - 如何从托管代码中捕获的 native 异常中获取 native 堆栈跟踪

c# - 如何在 WCF 服务上设置密码?

c# - 修改 OWIN OAuth 中间件以使用 JWT 不记名 token

.net - Visual Studio 2010 - WPF/Silverlight 和内置网格

interop - 消息系统设计