关于C# byte[]与struct的转换
转自: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));
[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;
{
throw new Exception("The method or operation is not implemented.");
}
};
{
//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);
}
}
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的转换的更多相关文章
- C# byte[]、struct、intptr等的相互转换
1.struct byte[]互相转换 //struct转换为byte[] public static byte[] StructToBytes(object structObj) { int siz ...
- C#使用struct直接转换下位机数据
编写上位机与下位机通信的时候,涉及到协议的转换,比较多会使用到二进制.传统的方法,是将数据整体获取到byte数组中,然后逐字节对数据进行解析.这样操作工作量比较大,对于较长数据段更容易计算位置出错. ...
- C# Byte[] 转String 无损转换
C# Byte[] 转String 无损转换 转载请注明出处 http://www.cnblogs.com/Huerye/ /// <summary> /// string 转成byte[ ...
- OpenCV中IplImage图像格式与BYTE图像数据的转换
最近在将Karlsruhe Institute of Technology的Andreas Geiger发表在ACCV2010上的Efficent Large-Scale Stereo Matchin ...
- byte与sbyte的转换
C#实现byte与sbyte的转换 byte[] mByte; sbyte[] mSByte = new sbyte[mByte.Length]; ; i < mByte.Length; i++ ...
- Java - byte[] 和 String互相转换
通过用例学习Java中的byte数组和String互相转换,这种转换可能在很多情况需要,比如IO操作,生成加密hash码等等. 除非觉得必要,否则不要将它们互相转换,他们分别代表了不同的数据,专门服务 ...
- C#string byte[] base64位互相转换
byte表示字节,byte[]则表示存放一系列字节的数组 1个字符=2个字节(byte) 1个字节=8个比特(bit) 网速上所说的1M其实是指1兆的小b,1M= 1024b/8 = 128kb 下面 ...
- Golang的Json encode/decode以及[]byte和string的转换
使用了太长时间的python,对于强类型的Golang适应起来稍微有点费力,不过操作一次之后发现,只有这么严格的类型规定,才能让数据尽量减少在传输和解析过程中的错误.我尝试使用Golang创建了一个公 ...
- php byte数组与字符串转换类
<?php /** * byte数组与字符串转化类 * @author ZT */ class Bytes { /** * 转换一个string字符串为byte数组 * @param $str ...
随机推荐
- php 生日提醒程序
<?php $startdate=time(); //当前时间 $birth="2013-05-13"; // 出生日期 $arr=explode(" ...
- C# 根据身份证号码获取简易信息
public class PackIden { /// <summary> /// 根据身份证获取生日 /// </summary> /// <param name=&q ...
- Linux上设置nginx支持https
1.前提条件 如果系统没有自带openssl,则需要安装. 2.生成证书 # .首先,进入你想创建证书和私钥的目录,例如: cd /etc/nginx/ # .创建服务器私钥,命令会让你输入一个口令: ...
- search in rotated sorted array leetcode
原题链接 题意:给你一个目标值,或者返回其在数组中的下标位置,或者返回-1(表示不存在,查找失败). 例如 0 1 2 4 5 6 7 可能成为 4 5 6 7 0 1 2. 思路分析: 用二分搜索来 ...
- border-radius(边框半径)
可以使用像素来指定border-radius的属性值使角变圆 除了像素,你还可以使用百分比来指定border-radius边框半径的值
- linux httpd 服务的安装
1.查看是否安装了httpd rpm -qa|grep httpd 2.安装httpd 使用yum 安装 yum -y install httpd 3.关闭防火墙和selinxu 4.使用fz软件或者 ...
- Fire uva 11624
题目连接:http://acm.hust.edu.cn/vjudge/problem/28833 /* 首先对整个图bfs一次得到火焰燃烧的时刻表 之后在bfs搜路径时加一个火烧表的判断 坑点在于:如 ...
- 用代码控制UI界面
public class MainActivity extends Activity { //当第一次创建Activity时回调该方法 @Override protected void ...
- 数据库知识整理<五>
简单的数据查询: 5.1查询的基本结构: Sql语句:select [distinct] (* | column [alias],...) from table [where condition] [ ...
- Html5前端框架
BootCss bootcss.com amazeui http://amazeui.org/