转自:http://blog.chinaunix.net/uid-215617-id-2213082.html

Some of the C# code I've been writing recently communicates via TCP/IP with legacy C++ applications. These applications use a raw packet format where C/C++ structures are passed back and forth.

Here is a simplified example of what the legacy code could look like:

#pragma pack(1)
typedef struct
{
int id;
char[] text;
} MESSAGE; // Send a message
MESSAGE msg;
msg.id = ;
strcpy(msg.text, "This is a test");
send(socket, (char*)&msg); // Receive a message
char buffer[];
recv(socket, buffer, );
MESSAGE* msg = (MESSAGE*)buffer;
printf("id=%d\n", msg->id);
printf("text=%s\n", msg->text);

The problem I was faced with was how to receive and handle this kind of message in a C# application. One method is to use BitConverter and Encoding.ASCII to grab the data field by field. This is tedious, prone to errors and easy to break of modifications are made in the future.

A better method is to marshal the byte array to a C# structure. Here is an example of how to do that marshaling:

using System;
using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Pack=)]
struct Message
{
public int id;
[MarshalAs (UnmanagedType.ByValTStr, SizeConst=)]
public string text;
} void OnPacket(byte[] packet)
{
GCHandle pinnedPacket = GCHandle.Alloc(packet, GCHandleType.Pinned);
Message msg = (Message)Marshal.PtrToStructure(
pinnedPacket.AddrOfPinnedObject(),
typeof(Message));
pinnedPacket.Free();
}

The GCHandle.Alloc call pins the byte[] in memory so the garbage collector doesn't mess with it. The AddrOfPinnedObject call returns an IntPtr pointing to the start of the array and the Marshal.PtrToStructure does the work of marshaling the byte[] to the structure.

If the actual structure data didn't start at the beginning of the byte array you would use the following assuming the structure data starts at position 10 of the array:

Message p = (Message)Marshal.PtrToStructure( Marshal.UnsafeAddrOfPinnedArrayElement(pinnedPacket, ), typeof(Message));
 
以下为何丹写的,关于C# byte[]与struct的转换
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        [Serializable()]
        public struct frame_t : ISerializable
        {
            //char数组,SizeConst表示数组的个数,在转换成
            //byte数组前必须先初始化数组,再使用,初始化
            //的数组长度必须和SizeConst一致
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
            public char[] headers;
            public int nbframe;
            public double seqtimes;
            public int deltatimes;
            public int w;
            public int h;
            public int size;
            public int format;
            public ushort bright;
            public ushort contrast;
            public ushort colors;
            public ushort exposure;
            public byte wakeup;
            public int acknowledge;
            #region ISerializable 成员
            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                throw new Exception("The method or operation is not implemented.");
            }
            #endregion
        };
    public class Struct_Transform
    {
        //struct转换为byte[]
        public static byte[] StructToBytes(object structObj)
        {
            int size = Marshal.SizeOf(structObj);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(structObj, buffer, false);
                byte[] bytes = new byte[size];
                Marshal.Copy(buffer, bytes, 0, size);
                return bytes;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        //byte[]转换为struct
        public static object BytesToStruct(byte[] bytes, Type strcutType)
        {
            int size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(bytes, 0, buffer, size);
                return Marshal.PtrToStructure(buffer, strcutType);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
    }

关于C# byte[]与struct的转换的更多相关文章

  1. C# byte[]、struct、intptr等的相互转换

    1.struct byte[]互相转换 //struct转换为byte[] public static byte[] StructToBytes(object structObj) { int siz ...

  2. C#使用struct直接转换下位机数据

    编写上位机与下位机通信的时候,涉及到协议的转换,比较多会使用到二进制.传统的方法,是将数据整体获取到byte数组中,然后逐字节对数据进行解析.这样操作工作量比较大,对于较长数据段更容易计算位置出错. ...

  3. C# Byte[] 转String 无损转换

    C# Byte[] 转String 无损转换 转载请注明出处 http://www.cnblogs.com/Huerye/ /// <summary> /// string 转成byte[ ...

  4. OpenCV中IplImage图像格式与BYTE图像数据的转换

    最近在将Karlsruhe Institute of Technology的Andreas Geiger发表在ACCV2010上的Efficent Large-Scale Stereo Matchin ...

  5. byte与sbyte的转换

    C#实现byte与sbyte的转换 byte[] mByte; sbyte[] mSByte = new sbyte[mByte.Length]; ; i < mByte.Length; i++ ...

  6. Java - byte[] 和 String互相转换

    通过用例学习Java中的byte数组和String互相转换,这种转换可能在很多情况需要,比如IO操作,生成加密hash码等等. 除非觉得必要,否则不要将它们互相转换,他们分别代表了不同的数据,专门服务 ...

  7. C#string byte[] base64位互相转换

    byte表示字节,byte[]则表示存放一系列字节的数组 1个字符=2个字节(byte) 1个字节=8个比特(bit) 网速上所说的1M其实是指1兆的小b,1M= 1024b/8 = 128kb 下面 ...

  8. Golang的Json encode/decode以及[]byte和string的转换

    使用了太长时间的python,对于强类型的Golang适应起来稍微有点费力,不过操作一次之后发现,只有这么严格的类型规定,才能让数据尽量减少在传输和解析过程中的错误.我尝试使用Golang创建了一个公 ...

  9. php byte数组与字符串转换类

    <?php /** * byte数组与字符串转化类 * @author ZT */ class Bytes { /** * 转换一个string字符串为byte数组 * @param $str ...

随机推荐

  1. WPF中ListBox的样式设置

    设置之后的效果为

  2. HDU 2689Sort it 树状数组 逆序对

    Sort it Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Sub ...

  3. iOS富文本的使用

    NSString *name = nil; if (_payNumber == 1) { name = [NSString stringWithFormat:@"向%@收款",na ...

  4. PHP开发模式之代理技术

    在实际开发中,我们经常要调用第三方的类库如SOAP服务等.使用这些第三方 组件并不难,最麻烦的莫过于调用了,一般的调试手段最方便的莫过于记日志了. 示例: 假如有以下第三方类库. // filenam ...

  5. python dict

    ###字典的基本结构 info = { "k1" : "v1", "k2" : "v2" } ###字典的valus可以 ...

  6. perl 对源文件内容修改 方法整理

    1, 利用Tie::File模块来直接对文件内容进行修改. #!/usr/bin/perl -w my $std="F160"; my $fast="FAST" ...

  7. 【Java学习笔记】<集合框架>对字符串进行长度排序

    package 测试; import java.util.Comparator; public class ComparatorByLength implements Comparator { //定 ...

  8. horizon 修改local的logging 配置

    再部署完horizon的开发环境后,首先要做的就是修改下logging的输出. 我用的开发软件是pycharm, 所以,为了方便在 console里看到输出.需要在 /home/geiao/repo/ ...

  9. Web大文件上传控件-bug修复-Xproer.HttpUploader6

    1.修复上传文件夹时,文件夹大小可能不正确的问题.这个问题是由于以MD5模式上传时没有更新文件夹总大小导致.   更新fd_complete.aspx   更新DBFile.cs-fd_complet ...

  10. Ubuntu安装sougou输入法

    1. 按照[1]的步骤进行,完美实现就好. 2. 必须重启后才能实现功能. Reference: [1] http://pinyin.sogou.com/linux/