C# 托管封送处理本机具有随机值

C# 托管封送处理本机具有随机值,c#,c++,memory,interop,C#,C++,Memory,Interop,我很难理解缓冲区中的某些值来自何处,以及为什么要获取System.ExecutionEngineeException 我的情况如下: 在我的系统中,我有一个通过命名管道与托管服务对话的本机应用程序。本机应用程序使用WriteFile(pipehandle,&msg,sizeof(msg),&cbBytes,NULL)发送由以下结构保存的数据: struct NotificationMessageHeader { __int32 A; __int64 B; __int32

我很难理解缓冲区中的某些值来自何处,以及为什么要获取System.ExecutionEngineeException

我的情况如下: 在我的系统中,我有一个通过命名管道与托管服务对话的本机应用程序。本机应用程序使用
WriteFile(pipehandle,&msg,sizeof(msg),&cbBytes,NULL)
发送由以下结构保存的数据:

struct NotificationMessageHeader
{
    __int32 A;
    __int64 B;
    __int32 MessageType;
    __int32 D;
};

struct NotificationMessageA
{
    NotificationMessageHeader Header;
    unsigned char X;
    wchar_t Y[MAX_PATH];
};
托管服务具有以下结构的托管版本:

[StructLayout(LayoutKind.Sequential)]
public struct NotificationMessageHeader
{
    public UInt32 A;
    public UInt64 B;
    public UInt32 MessageType;
    public UInt32 D;
}

[StructLayout(LayoutKind.Sequential)]
public struct NotificationMessageA
{
    public NotificationMessageHeader Header;
    [MarshalAs(UnmanagedType.I1)]
    public byte X;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string Y;
}
当我从本机应用程序发送数据时,我要做的第一件事是将缓冲区读入通用结构:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct GenericNotificationMessage
{
    public NotificationMessageHeader Header;
}
为了确定消息类型,在确定消息类型受支持后,我使用此函数将该缓冲区的其余部分解码为适当的结构:

    T GetMessageAsStructure<T>(object data)
        where T : struct
    {
        T output = default(T);
        GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
        try
        {
            IntPtr dataPtr = handle.AddrOfPinnedObject();
            output = (T)Marshal.PtrToStructure(dataPtr, typeof(T));
        }
        finally
        {
            handle.Free();
        }
        return output;
    }
托管缓冲区具有以下值:

[0] 2 <---- This shouldn't be at index 3?
[1] 0
[2] 0
[3] 0
[4] 0
[5] 0
[6] 0
[7] 0
[8] 231 <--- WTF is this? should't it start at index 11?
[9] 3
[10] 0
[11] 0
[12] 0
[13] 0
[14] 0
[15] 0
[16] 1
[17] 0
[18] 0
[19] 0
[20] 3
[21] 0
[22] 0
[23] 0
[24] 64
[25] 0
[26] 115
[27] 0
[28] 111
[29] 0
[30] 109
[31] 0
[32] 101
[33] 0
[34] 101
[35] 0
[36] 120
[37] 0
[38] 101
[39] 0
[40] 99
[41] 0
[42] 46
[43] 0
[44] 101
[45] 0
[46] 120
[47] 0
[48] 101
[49] 0
[50] 0

[0]2您正在将
NotificationMessageA.Y
编组为指针,但在本机代码中,它是结构内部的缓冲区,而不是指针,除了MiMo的答案之外,您还应该使用
非托管类型。ByValTStr

Index 0 to 3: MessageHeader.A, little endian
Index 4 to 7: padding, since B must be 8 byte aligned
Index 8 to 15: B, little endian
...
Index 24: X
Index 25: padding
Index 26: start of the wchar_t array Y, but will be incorrectly interpreted as a pointer

工作得很好!谢谢你,现在说得通了。。。谢谢
Index 0 to 3: MessageHeader.A, little endian
Index 4 to 7: padding, since B must be 8 byte aligned
Index 8 to 15: B, little endian
...
Index 24: X
Index 25: padding
Index 26: start of the wchar_t array Y, but will be incorrectly interpreted as a pointer