我在C#中有这个代表。
public delegate string ACSharpDelegate(string message);
我将如何创建一个托管C ++ .dll,它将接受此委托作为参数,以便C ++ .dll可以调用它?
答案 0 :(得分:6)
您需要至少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 ();
}
}
}