关于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 ...
随机推荐
- Codeforces 723C. Polycarp at the Radio 模拟
C. Polycarp at the Radio time limit per test: 2 seconds memory limit per test: 256 megabytes input: ...
- CPU的内部架构和工作原理
一直以来,总以为CPU内部真是如当年学习<计算机组成原理>时书上所介绍的那样,是各种逻辑门器件的组合.当看到纳米技术时就想,真的可以把那些器件做的那么小么?直到看了Intel CPU制作流 ...
- iOS键盘出现时界面跟着往上推
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UI ...
- 检查css没被引用上的问题
1.外部链接是否对的. 2.设置的命名是否一致或同名设置了 3.删除添加的注释看看
- Android中轴旋转特效实现,制作别样的图片浏览器
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/10766017 Android API Demos中有很多非常Nice的例子,这些例 ...
- Exception in thread “main” com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: empty String
String json="A valid json"; Job job = new Gson().fromJson(json, Job.class); Exception in t ...
- nodejs: 理解Buffer
学习nodejs中buffer这一章,有一段写到buffer的拼接,其中一段源码非常优美,特拿来与大家共享. var chunks = []; var size = 0; res.on('data', ...
- MySQL Connector/J 6.x jdbc.properties 配置, mysql-connector-java-6.0.4.jar 异常
今天学习SSM框架整合,完成Spring和mybatis这两大框架的整合做测试时候出来很多问题,主要来自于配置文件. 我这里重点说一下Mysql数据驱动配置. 配置pom.xml时候去网站 MySQL ...
- 安装Pomelo 时遇到的坑
一.Pomelo相关的代码地址 https://github.com/NetEase,这里面包含比较多的项目. 2. https://github.com/NetEase/pomelo/wiki/%E ...
- Dynamic CRM 2013学习笔记(四十)流程3 - 对话(Dialog)用法图解
我们将用对话来实现一个简单的满意度调查,下一个问题依赖于上一个问题.对话是同步的,不同于工作流既可以是同步也可以是异步的:对话可以跟用户互动:对话只能手动开始:对话只支持 .Net Framework ...