简体   繁体   English

如何将C#委托函数传递给Managed C ++ .Dll?

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

I have this delegate in C#. 我在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? 我将如何创建将接受此委托作为参数的托管C ++ .dll,以便C ++ .dll可以调用它?

You'll need at least 3 assemblies to avoid circular references. 您至少需要3个程序集才能避免循环引用。

C# library: 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 library (references CSLibrary): 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# program (references CSLibrary and CPPLibrary): 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 ();
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将结构从C#托管结构传递到C ++非托管DLL并得到结果结构? - How can I pass struct from C# managed to C++ unmanaged DLL and get struct in result? 在托管C ++中使用函数指针调用C#委托 - Call C# delegate with function pointer in Managed C++ 如何将函数指针从C#传递给C ++ Dll? - How to pass function pointer from C# to a C++ Dll? 在 C++ 中使用回调函数 C# 委托 dll - Using Call Back Function C# delegate dll in C++ 如何将字符串参数从 C++ 传递到托管 C# DLL - How to pass a string argument from C++ to a managed C# DLL 有没有办法在 C# 中挂钩托管 function ,就像我在 ZF6F87C9FDCF8EEB713C 中的非托管 function 一样? - Is there a way to hook a managed function in C# like I would a unmanaged function in C++? 在c#中使用托管c ++ dll - using managed c++ dll in c# 通过托管C ++包装程序从非托管C ++ dll运行C#函数 - Run a C# function from an unmanaged C++ dll through a managed C++ Wrapper 从C#调用非托管C ++库(dll):如何在托管代码和非托管代码之间正确传递数据 - Calling unmanaged C++ library (dll) from C# : How to properly pass data between managed and unmanaged code 如何将委托或函数指针从C#传递给C ++并使用InternalCall在那里调用它 - How to pass a delegate or function pointer from C# to C++ and call it there using InternalCall
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM