[英]Passing C# function pointers into C++/CLI interop dll
我正在尝试将一个函数指针从C#传递到C ++ / CLI并得到一个Windows编译器错误,指出该语言不支持ManagedTakeCallback
函数(C#) - 我在C ++ / CLI互操作中定义了ManagedTakeCallback
。 我的代码看起来像
C#应用程序:
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 interop dll h和cpp文件:
//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();
}
然后,C ++ / CLI互操作层调用C DLL。 我可以调用ManagedAdd
互操作函数; 但是,如果添加了ManagedTakeCallback
,则会出现Windows编译器错误。 我怀疑C#应用程序没有通过ManagedTakeCallback
函数正确编组函数指针,或者C ++ / CLI端的签名不正确? 我非常感谢任何见解。
以下是现场评论:
“但是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.