5
我在C#中有這個代表。如何將C#委託函數傳遞給託管C++ .Dll?
public delegate string ACSharpDelegate(string message);
我怎麼會去有關創建一個託管C++的.dll會接受這個委託作爲參數,因此C++ .dll文件能打電話嗎?
我在C#中有這個代表。如何將C#委託函數傳遞給託管C++ .Dll?
public delegate string ACSharpDelegate(string message);
我怎麼會去有關創建一個託管C++的.dll會接受這個委託作爲參數,因此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();
}
}
}