zoukankan
html css js c++ java
从struct到byte[]之RawFormatter
public
partial
class
Form1 : Form
{
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
Demo d
=
new
Demo();
d.a
=
5
;
d.b
=
10
;
d.c
=
new
byte
[]
{
1
,
2
,
3
}
;
d.s
=
"
123
"
;
byte
[] buf
=
RawFormatter.RawSerialize(d);
MessageBox.Show(
"
aaa
"
);
}
}
[StructLayout(LayoutKind.Sequential,Pack
=
1
,CharSet
=
CharSet.Ansi)]
struct
Demo
{
public
byte
a;
public
int
b;
[MarshalAs(UnmanagedType.ByValArray, SizeConst
=
3
)]
public
byte
[] c;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst
=
5
)]
public
string
s;
}
public
class
RawFormatter
{
public
static
byte
[] RawSerialize(
object
anything)
{
int
rawsize
=
Marshal.SizeOf(anything);
IntPtr buffer
=
Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(anything, buffer,
false
);
byte
[] rawdatas
=
new
byte
[rawsize];
Marshal.Copy(buffer, rawdatas,
0
, rawsize);
Marshal.FreeHGlobal(buffer);
return
rawdatas;
}
public
static
object
RawDeserialize(
byte
[] rawdatas, Type anytype)
{
int
rawsize
=
Marshal.SizeOf(anytype);
if
(rawsize
>
rawdatas.Length)
return
null
;
IntPtr buffer
=
Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawdatas,
0
, buffer, rawsize);
object
retobj
=
Marshal.PtrToStructure(buffer, anytype);
Marshal.FreeHGlobal(buffer);
return
retobj;
}
}
QQ:273352165 evlon#126.com 转载请注明出处。
查看全文
相关阅读:
大数据下高并发的处理详解
【玩转TensorFlow】TensorFlow常见问题详解
在阿里云上两分钟玩转AlextNet
【前端精华】React源码分析系列
svm
神经网络结构选择
神经网络反向传播跳出局部极小
ubuntu16.04设置电池充电阈值
pandas datafram重命名列名称
centos6.8/ubuntu 安装python2.7 or python3.6
原文地址:https://www.cnblogs.com/evlon/p/865272.html
最新文章
企业一把手为什么要“装聋作哑”
poj 3228 Gold Transportation 二分+网络流
bzoj 3289: Mato的文件管理 莫队+线段树
bzoj 2038: [2009国家集训队]小Z的袜子(hose) 莫队算法
codeforces 603C. Lieges of Legendre sg函数
poj 3592 Instantaneous Transference 缩点+最长路
poj 1949 Chores 最长路
poj 1724 ROADS 最短路
hdu 4888 Redraw Beautiful Drawings 网络流
hdu 4735Little Wish~ lyrical step~ 重复覆盖
热门文章
hdu 3980 Paint Chain sg函数
webstorm字体大小设置
web前端涉及到的软件
关于form导致的作用域变化问题
哪门编程语言工资最高?YouWorth和StackOverFlow的数据来说话
简单读懂人工智能:机器学习与深度学习是什么关系
从人脑研究入手_使人工智能不再“四肢发达_头脑简单”
“NASA”计划背后_阿里巴巴大数据系统架构概述
Oracle迁移到MySQL性能下降的注意点
【MySQL性能优化】MySQL常见SQL错误用法
Copyright © 2011-2022 走看看