2013-12-16 65 views
0

C#代码:互操作通结构从C#到C++

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 
public struct Message 
{ 
    public uint MsgId; 
    public uint DLC; 
    public uint Handle; 
    public uint Interval; 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] 
    public byte[] Data; 
}; 

我有这样的结构,如下所示发送给一个函数在C++天然的.dll:

[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)] 
    [return: MarshalAs(UnmanagedType.U4)] 
    public static extern int AFT_iSetRTSECANWrapper(IntPtr Data); 

我正在准备的缓冲器像这样:

 Message frame = new Message(); 
     frame.MsgId = (uint)MsgId; 
     frame.DLC = (uint)DLC; 
     frame.Interval = (uint)Interval; 

     frame.Data = new byte[64]; 

     for (int i = 0; i < Data.Length; i++) 
     { 
      frame.Data[i] = 11; 
     } 

     //Transmit message 
     int rawsize = Marshal.SizeOf(frame); 
     IntPtr frameBuffer = Marshal.AllocHGlobal(rawsize); 
     Marshal.StructureToPtr(frame, frameBuffer, false); 

     AFT_iSetRTSECANWrapper(frameBuffer); 
在C++

我有以下结构:

typedef struct { 
unsigned int MsgId; 
unsigned int DLC; 
unsigned int Handle; 
unsigned int Interval; 
    unsigned char Data[64]; 
} Message; 

和被调用的函数是这样的:

extern "C" __declspec(dllexport) int AFT_iSetRTSECANWrapper(Message *data) 

此我只是尝试访问域在消息与数据 - > DLC后,但我什么也没得到。我无法弄清楚这里有什么问题。

+0

的sizeof(char)的==的sizeof(字节),所以它应该是“unsigned char Data [8]” – Matt

+0

我没有看到任何错误。什么“我什么都没有”是什么意思?使用调试器查看“数据”,您至少应该看到数组中的0x0b字节值。 –

回答

0

我猜数据没有与结构的其余部分分配在相同的连续部分,所以它不会被传输。尝试

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 
public struct Message 
{ 
    public uint MsgId; 
    public uint DLC; 
    public uint Handle; 
    public uint Interval; 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] 
    public byte[] Data = new byte[64]; 
}; 

对于C++位,而不是转移到一个IntPtr,直接转移

[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)] 
[return: MarshalAs(UnmanagedType.U4)] 
public static extern int AFT_iSetRTSECANWrapper([in,out] Message Data); 

发消息作为

Message frame = new Message(); 
frame.MsgId = (uint)MsgId; 
frame.DLC = (uint)DLC; 
frame.Interval = (uint)Interval; 
for (int i = 0; i < Data.Length; i++) 
{ 
    frame.Data[i] = 11; 
} 

//Transmit message 
AFT_iSetRTSECANWrapper(frame);