我正在尝试将一个函数指针从C#传递到C ++ / CLI并得到一个Windows编译器错误,指出该语言不支持ManagedTakeCallback
函数(C#) - 我定义了{{1在C ++ / CLI互操作中。我的代码看起来像
C#应用程序:
ManagedTakeCallback
和
C ++ / CLI interop dll h和cpp文件:
namespace ManagedConsoleApplication
{
class Callback
{
public delegate double DelegateAdd(double value1, double value2);
public static double CallbackAdd(double value1, double value2)
{
return value1 + value2;
}
public static DelegateAdd delegateCallback = new DelegateAdd(Callback.CallbackAdd); //declare as static to prevent GC
}
class Program
{
// [DllImport("InteropDLL.dll", CallingConvention = CallingConvention.StdCall)]
// public static extern void ManagedCallback(IntPtr pCallback);
static void Main(string[] args)
{
InteropDLL io = new InteropDLL();
Console.WriteLine("The Add return = {0}", io.ManagedAdd(3, 2));
Console.WriteLine("Pass CallBack to Unmanaged code");
Callback cb = new Callback();
IntPtr intptr_delegate = Marshal.GetFunctionPointerForDelegate(Callback.delegateCallback); //convert delegate to function pointer which can be used by unmanaged code
Console.WriteLine("The callback return is {0}", io.ManagedTakeCallback(intptr_delegate));
Console.WriteLine("Please hit Enter to exit");
String value = Console.In.ReadLine();
//Console.WriteLine("End of program ", value);
}
}
}
然后,C ++ / CLI互操作层调用C DLL。我可以调用//HEADER
namespace Interop
{
typedef double (__stdcall *PCallback)(double value1, double value2);
public ref class InteropDLL
{
public:
double ManagedAdd(double value1, double value2);
public:
double ManagedTakeCallback(PCallback pCallback);
};
}
//CPP
double Interop::InteropDLL::ManagedAdd(double value1, double value2)
{
return NativeAdd(value1, value2);
}
double Interop::InteropDLL::ManagedTakeCallback(PCallback pCallback)
{
return NativeTakeCallback();
}
互操作函数;但是,如果添加ManagedAdd
,则会出现Windows编译器错误。我怀疑C#应用程序没有通过ManagedTakeCallback
函数正确编组函数指针,或者C ++ / CLI端的签名不正确?我非常感谢任何见解。
答案 0 :(得分:0)
以下是网站上的评论:
“但是C#不支持C ++函数指针,所以我们不能在这里调用C ++函数指针.C#只有Delegate对象,我们必须通过Marshal.GetDelegateForFunctionPointer将函数指针转换为Delegate。它在System中声明。 Runtime.InteropServices如下:
public static Delegate GetDelegateForFunctionPointer ( IntPtr ptr, Type t)
获得完整答案的链接: http://www.codeproject.com/Articles/27298/Dynamic-Invoke-C-DLL-function-in-C