转自: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. jquery 让select元素中的某个option被选中

    jquery 操作select 取值,设置选中值 博客分类: javaScript selecttextvalue取值设置选中值 比如 <select class="type" ...

  2. Sublime Text 3常用快捷键 以及package control 安装

    网络上搜索到的,现整理下来备用: package control安装 view下 ctrl+~ import urllib.request,os; pf = 'Package Control.subl ...

  3. 【java】:通用接口

    电商接口 京东获取单个商品价格接口: http://p.3.cn/prices/mgets?skuIds=J_商品ID&type=1 用例 ps:商品ID这么获取:http://item.jd ...

  4. 《深入理解Spark:核心思想与源码分析》一书正式出版上市

    自己牺牲了7个月的周末和下班空闲时间,通过研究Spark源码和原理,总结整理的<深入理解Spark:核心思想与源码分析>一书现在已经正式出版上市,目前亚马逊.京东.当当.天猫等网站均有销售 ...

  5. SGU196_Matrix Multiplication

    给一个无向图,如果第i个点连接第j条边,那么mat[i][j]=1,否则mat[i][j]=0. 求mat的转置乘以本身得到的矩阵每个位置的和是多少? 理解矩阵的意义就比较好做了. mat[i][j] ...

  6. 常用Sql语句书写

    一.增:有2种方法 1.使用insert插入单行数据: 语法:insert [into] <表名> [列名] values <列值> 例:insert into Strdent ...

  7. 何为“精通Java”

    何为精通Java?本来Java仅仅是一门语言,但从应用技术的角度来看,精通Java是可以无边无际的.很可能你可以对James说:我精通J2EE.JVM.Java服务器.大数据等等一些和Java相关的应 ...

  8. EditText的hint不显示

    EditText的hint不显示可能的原因: 1.字体颜色与EditText的背景色一样; 2.使用了android:inputType = phone; 3.如果加上android:ellipsiz ...

  9. Java入门1dayCode

    public class HelloWorld { /* * 多行注释方式 * main()方法: java语言的入口方法(函数) */ public static void main(String[ ...

  10. android中掩码的使用

    掩码是一串二进制代码对目标字段进行位与运算,屏蔽当前的输入位,所以有时又称为屏蔽码. 在Android中常使用这种技巧设置flag来判断标记,具体实现可参考framework层的WindowManag ...