Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all articles
Browse latest Browse all 1710

About C# P/invoke a callback function in a c++ struct.

$
0
0

Hi all,

I received an SDK suite from a third party company, so I have no clue how its methods were implemented. All I have got is the documentation from the company. The SDK is written in C++. In this SDK, I encountered an odd callback implementation that is different from the "normal" callback I have seen before.

According to the document, there is a struct 

NET_EHOME_CMS_LISTEN_PARAM,

and it looks like this:

structNET_EHOME_CMS_LISTEN_PARAM
{
  // ip address for some device
  NET_EHOME_IPADDRESS    struAddress;
  // odd callback here!
  DEVICE_REGISTER_CB fnCB;
  void *pUser; //pointer user data
  BYTE byRes[32]; //document indicates set to 0.
}

in C#, I wrapped the struct like this:

[StructLayoutAttribute(LayoutKind.Sequential)]
public struct NET_EHOME_CMS_LISTEN_PARAM
{
  public NET_EHOME_IPADDRESS structAddress;
  public DEVICE_REGISTER_CB fnCB;
  public IntPtr pUser;
  [MarshalAsAttribute(UnmanagedType.ByValArray,
  SizeConst = 32, ArraySubType = UnmanagedType.I1)]
  public byte[] byRes;
}

and also the callback:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool DEVICE_REGISTER_CB(
  Int32 iUserID,
  UInt32 dwDataType,
  ref NET_EHOME_DEV_REG_INFO pOutBuffer,
  UInt32 dwOutLen,
  ref NET_EHOME_SERVER_INFO pInBuffer,
  UInt32 dwInLen,
  ref IntPtr pUser);


This is how I use the callback function:

lpCMSListenPara.fnCB = new EHomeSDKCS.DEVICE_REGISTER_CB(DeviceRegisterCB);

notice that the lpCMSListenPara is the struct's new object.

The callback did not invoke at all after the struct is taken as the parameter in the method shown below: (according to the document, this is the only parameter "StartListen" method takes)

// Method that uses the struct
iHandle = EHomeSDKCS.NET_ECMS_StartListen(ref lpCMSListenPara);

Is it the correct way to implement a callback in a c++ struct or did I do something wrong? I tried to search a solution to this sort of situation on MSDN but I did not find any precedent, thus the question here.

Thanks a lot,

J.H






Viewing all articles
Browse latest Browse all 1710

Trending Articles