由 C# 傳 Callback function 給 C++ DLL
一般來說,在 C# 呼叫 C++ 寫的 DLL ,可以用下面的方式來宣告:
public class ClassA
{
const string dllPath = @"pathToTheDLL.dll";
[DllImport(dllPath)]
public extern static void FuncionA(string argA);
….
public ClassA() // constructor
{
}
void callFunctionA(string argA)
{
FunctionA(argA);
}
}
{
const string dllPath = @"pathToTheDLL.dll";
[DllImport(dllPath)]
public extern static void FuncionA(string argA);
….
public ClassA() // constructor
{
}
void callFunctionA(string argA)
{
FunctionA(argA);
}
}
啊不過之前在寫程式時遇到麻煩,就是要傳個 callback function 進去,這就很困擾了。中間的過程就不贅述了。
好像是 .Net 2.0 之後,由 C# 呼叫 (unmanaged) C++ 所作出的 DLL ,就可以直接如下寫:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int Filter(string input, string matched);
public class ClassA
{
[DllImport(dllPath)]
public extern static int FuncionB(string argA, Filter callback);
…
}
public delegate int Filter(string input, string matched);
public class ClassA
{
[DllImport(dllPath)]
public extern static int FuncionB(string argA, Filter callback);
…
}
當然, CallingConvention 視你用的是什麼而定。
Ref:


