我想馬歇爾c回調是在一個結構。我很確定我有一切正確的,但是當使用我的C#示例我不會得到事件,當使用c + +我會得到事件。C#編組回調
這裏是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 + +。
struct callBacks;
callbacks.dataArriveNotif = &dataArriveNotif;
callbacks.sendFailureNotif = &sendFailureNotif;
SetCallbacks(callBacks);
使用調試器,啓用非託管代碼調試。在進行回調調用的C代碼(不可見)和C#DataArrived方法上設置斷點。 – 2011-03-09 19:55:26
我實際上已經進入了SetCallbacks,並且結構具有所有Null值,這是怎麼發生的? – Will 2011-03-09 21:30:32
我不知道。試用Marshal.StructureToPtr查看結構編組是否正確。 – 2011-03-09 21:48:53