[英]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.