C#编组回调 [英] C# Marshalled Callbacks
问题描述
我正在尝试Marshall c回调结构中的回调.我很确定自己一切正确,但是在使用C#示例时,我没有事件,在使用c ++时,我确实得到了事件.
I am trying to Marshall c call backs that are in a struct. I am pretty sure I have everything correct, but when using my C# example I don't get events, when using c++ I do get events.
这是C#
class Program
{
[DllImport("Some.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern int SetCallbacks(Callbacks callBack);
static Callbacks Callback = new Callbacks { DataArrived = DataArrived, SendFailure = SendFailure };
static void Main(string[] args)
{
SetCallbacks(Callback);
Console.ReadLine();
}
static void DataArrived(uint id, IntPtr data)
{
}
static void SendFailure(uint id, uint id2, IntPtr data)
{
}
}
[StructLayout(LayoutKind.Sequential)]
public struct Callbacks
{
public DataArrived DataArrived;
public SendFailure SendFailure;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void DataArrived(uint id, IntPtr data);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void SendFailure(uint id, uint id2, IntPtr ulpData);
这来自C头文件.
struct callBacks
{
void (*dataArriveNotif) (unsigned int, void*);
void (*sendFailureNotif) (unsigned int, unsigned int, void*);
}
int SetCallbacks(callBacks callBacks);
这是正在工作的c ++.
Here is the working c++.
struct callBacks;
callbacks.dataArriveNotif = &dataArriveNotif;
callbacks.sendFailureNotif = &sendFailureNotif;
SetCallbacks(callBacks);
推荐答案
与委托进行的所有处理实际上都是正确的.在示例中,我对senario进行了一些简化.
Everything dealing with the delegate was actually correct. I simplified the senario a little bit in the example.
public static extern int SetCallbacks(Callbacks callBack);
实际上是
public static extern int SetCallbacks(String[] array, Callbacks callBack);
字符串数组的末尾有很多结尾的0.这使得回调结构全部为空.我放弃了尝试以正确的方式封送string []的方法,只是将其设置为Intptr,一切开始正常工作.
The string array had lots of trailing 0's at the end. Which made the callback struct all nulls. I gave up trying to marshal the string[] the correct way and just made it a Intptr and everything started working.
这篇关于C#编组回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!