简体   繁体   English

C#/ C ++回调传递为NULL

[英]C#/C++ Callback Passed as NULL

I am having some trouble passing a callback function from C# to a C++ unmanaged DLL. 我在将回调函数从C#传递到C ++非托管DLL时遇到了一些麻烦。 When running the program theDLL receives NULL instead of the callback. 运行程序时,DLL接收到NULL而不是回调。

The callback function is defined as 回调函数定义为

typedef void(__cdecl *CallbackFunction)();

The C++ functions is defined as C ++函数定义为

__declspec(dllexport) void __cdecl StreamData(unsigned char *Buffer, unsigned int BufferSize, unsigned long Points,
 unsigned short AveragingPower, CallbackFunction BufferUpdated);

The C# callback and function delegates are defined as C#回调和函数委托定义为

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void BufferUpdatedCallback();

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void StreamDataDelegate(byte[] Buffer, uint BufferSize, ulong Points,
 ushort AveragingPower, BufferUpdatedCallback BufferUpdated);

The C++ function definitly works correctly as I have tested it from a C++ Console application and it works correctly. 我已经从C ++控制台应用程序对其进行了测试,因此C ++函数绝对可以正常工作,并且可以正常工作。 In C# I can acquire a pointer for the delegate of the callback via Marshal.GetFunctionPointer(Delegate d) however when I step through the program at the point it enters the StreamData function the pointer becomes NULL inside the DLL. 在C#中,我可以通过Marshal.GetFunctionPointer(Delegate d)获取该回调的委托的指针,但是当我逐步进入该程序的点进入StreamData函数时,该指针在DLL内部变为NULL。 The calling conventions are consistent across the DLL and the C# delegates. 调用约定在DLL和C#委托之间是一致的。

Am I missing something quite basic? 我缺少基本的东西吗? And does anybody know of a way of correcting the problem? 有人知道解决问题的方法吗?

UPDATE UPDATE

If the unsigned long Points parameter is removed from both the DLL and C# then the function works correctly, otherwise the callback is NULL. 如果从DLL和C#中都删除了unsigned long Points参数,则该函数将正常运行,否则回调为NULL。

An unsigned long in the C++ compiler is a 32-bit integer type. C ++编译器中的unsigned long是32位整数类型。 You however declared as ulong , a 64-bit type. 但是,您将其声明为64位类型的ulong The argument misalignment this causes makes the delegate look like NULL in the C++ code, it is reading the upper 32-bits of that ulong variable. 这会导致参数不对齐,导致委托在C ++代码中看起来像NULL,它正在读取该ulong变量的高32位。

You must use uint in your [DllImport] declaration for the Points argument. 您必须在[DllImport]声明中为Points参数使用uint

Try this: 尝试这个:

private delegate void StreamDataDelegate(ref byte[] Buffer, uint BufferSize, ulong Points, ushort AveragingPower, BufferUpdatedCallback BufferUpdated); 私有委托void StreamDataDelegate(ref byte [] Buffer,uint BufferSize,ulong Points,ushort AveragingPower,BufferUpdatedCallback BufferUpdated);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM