VC ++ __stdcall callbacks in C #

I am working on a C # application that needs to be called in a C ++ dll. It seems that all calls work except one, in particular. From the C ++ header file, the function and callback signature are as follows:

typedef void (__stdcall *LPFNDLL_RECEIVE_CALLBACK)(CANMsg*); USBCANPLUS_API CAN_STATUS __stdcall canplus_setReceiveCallBack( CANHANDLE handle, LPFNDLL_RECEIVE_CALLBACK cbfn ); 

Based on the readings, I have a setup and an inner class that complete the call as such:

 [DllImport("USBCanPlusDllF.dll")] public static extern int canplus_setReceiveCallBack(int handle, CallbackDelegate callback); [UnmanagedFunctionPointerAttribute(CallingConvention.StdCall)] public delegate void CallbackDelegate(ref CANMsg msg); 

And used as:

  private static void callback(ref EASYSYNC.CANMsg msg) { Debug.Print(msg.id + ":" + msg.timestamp + ":" + msg.flags + ":" + msg.len + ":" + msg.data); } static EASYSYNC.CallbackDelegate del = new EASYSYNC.CallbackDelegate(callback); private void button1_Click(object sender, EventArgs e) { int handle = EASYSYNC.canplus_Open(IntPtr.Zero, "1000", IntPtr.Zero, IntPtr.Zero, 0); if(handle > 0) { int result = EASYSYNC.canplus_setReceiveCallBack(handle, del); } } 

I know that the problems with C ++ callbacks in C # are complex and have read a little on this subject, so I have the code above. My problem is that my code falls into int result = .... line, the whole program goes out for lunch, indicating that I'm probably still something wrong with the callback handling. Can anyone advise?

+4
source share
1 answer

I'm a little unsure of this, but you pointed out that the convention on calling a delegate should be StdCall (which should be because it says C / C ++ code), but you didn't do it for the dllimport function canplus_setReceiveCallBack () declaration, it works Does she when you do the following:

 [DllImport("USBCanPlusDllF.dll", CallingConvention=CallingConvention.StdCall)] public static extern int canplus_setReceiveCallBack(int handle, CallbackDelegate callback); 

As I said, I'm not sure, but this can be a problem.

0
source

All Articles