首页 > 编程语言 >C#在文件读写结构体 Marshal效率低

C#在文件读写结构体 Marshal效率低

时间:2023-04-17 18:33:43浏览次数:31  
标签:C# TestStruct 读写 System ts buffer using Marshal


using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Windows.Forms;

 using System.IO;
 using System.Runtime.InteropServices;

 namespace WindowsFormsApplication2
 {
 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
 }

 private void button1_Click(object sender, EventArgs e)
 {
 string strFile = Application.StartupPath + "\\test.dat";
 if (!File.Exists(strFile))
 {
 MessageBox.Show("文件不存在");
 return;
 }

 FileStream fs = new FileStream(strFile, FileMode.Open,

 FileAccess.ReadWrite);
 TestStruct ts = new TestStruct();
 byte[] bytData = new byte[Marshal.SizeOf(ts)];
 fs.Read(bytData, 0, bytData.Length);
 fs.Close();
 ts = rawDeserialize(bytData);
 textBox1.Text = ts.dTest.ToString();
 textBox2.Text = ts.uTest.ToString();
 textBox3.Text = Encoding.Default.GetString(ts.bTest);
 }

 private void button2_Click(object sender, EventArgs e)
 {
 string strFile = Application.StartupPath + "\\test.dat";
 FileStream fs = new FileStream(strFile, FileMode.Create,
 FileAccess.Write);
 TestStruct ts = new TestStruct();
 ts.dTest = double.Parse(textBox1.Text);
 ts.uTest = UInt16.Parse(textBox2.Text);
 ts.bTest = Encoding.Default.GetBytes(textBox3.Text);
 byte[] bytData = rawSerialize(ts);
 fs.Write(bytData, 0, bytData.Length);
 fs.Close();
 }

 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] //,Size=16
 public class TestStruct
 {
 [MarshalAs(UnmanagedType.R8)] //,FieldOffset(0)] 
 public double dTest;
 [MarshalAs(UnmanagedType.U2)] //, FieldOffset(8)]
 public UInt16 uTest;
 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
 //, FieldOffset(10)]
 public byte[] bTest;
 }

 //序列化
 public static byte[] rawSerialize(object obj)
 {
 int rawsize = Marshal.SizeOf(obj);
 IntPtr buffer = Marshal.AllocHGlobal(rawsize);
 Marshal.StructureToPtr(obj, buffer, false);
 byte[] rawdatas = new byte[rawsize];
 Marshal.Copy(buffer, rawdatas, 0, rawsize);
 Marshal.FreeHGlobal(buffer);
 return rawdatas;
 }

 //反序列化
 public static TestStruct rawDeserialize(byte[] rawdatas)
 {
 Type anytype = typeof(TestStruct);
 int rawsize = Marshal.SizeOf(anytype);
 if (rawsize > rawdatas.Length)
 return new TestStruct();
 IntPtr buffer = Marshal.AllocHGlobal(rawsize);
 Marshal.Copy(rawdatas, 0, buffer, rawsize);
 object retobj = Marshal.PtrToStructure(buffer, anytype);
 Marshal.FreeHGlobal(buffer);
 return (TestStruct)retobj;
 }
 }
 }

标签:C#,TestStruct,读写,System,ts,buffer,using,Marshal
From: https://blog.51cto.com/u_16076050/6195834

相关文章

  • elementui select下来内容过长问题解决方案
    :popper-append-to-body="false"必写自定义显示<divclass="select-flow">{{dict.declareConditions}}</div>自定义css样式el-option添加title属性 <el-selectv-model="formData.declCondition"placeholder="请选择"sty......
  • ASP.NET Core MVC 从入门到精通之布局
    随着技术的发展,ASP.NETCoreMVC也推出了好长时间,经过不断的版本更新迭代,已经越来越完善,本系列文章主要讲解ASP.NETCoreMVC开发B/S系统过程中所涉及到的相关内容,适用于初学者,在校毕业生,或其他想从事ASP.NETCoreMVC系统开发的人员。 经过前几篇文章的讲解,初步了解ASP.NETCor......
  • 用reflector看到C#Random类的实现
    [Serializable,ComVisible(true)]publicclassRandom{//Fieldsprivateintinext;privateintinextp;privateconstintMBIG=0x7fffffff;privateconstintMSEED=0x9a4ec86;privateconstintMZ=0;privateint[]SeedArray;//MethodspublicRandom(......
  • docker Ubuntu 安装教程
    启动docker镜像dockerrun-t-i-dubuntu:18.04/bin/bash配置ustc镜像源sed-i's@//.*archive.ubuntu.com@//mirrors.ustc.edu.cn@g'/etc/apt/sources.listsed-i's/security.ubuntu.com/mirrors.ustc.edu.cn/g'/etc/apt/sources.listapt-getcleanap......
  • c# 扩展方法
    由来一个类想要有新的方法,除了简单粗暴的在类中直接添加,当然可以用继承来实现,不过若为扩展一个方法就用继承,这就大材小用了,况且有些类是不能被继承的。于是乎,c#3.0提出了扩展方法,用它来为现有的类型(比如自定义的类)添加方法。如何定义扩展方法a)扩展方法必须在非嵌套(类中类)非......
  • opencv c++ 保存为位深度为1的png
    vector<int>compression_params;compression_params.push_back(IMWRITE_PNG_COMPRESSION);compression_params.push_back(3);compression_params.push_back(IMWRITE_PNG_BILEVEL);compression_params.push_back(1);imwrite("text2.png&......
  • 文本编辑器 实现ctrl+v粘贴图片并上传、word粘贴带图片
    ​ 当前功能基于PHP,其它语言流程大抵相同。大概流程:1.将docx文件上传到服务器中2.使用PHPoffice/PHPword实现将word转换为HTML3.将HTML代码返回并赋值到编辑器中 1编辑器配置修改1.1新增上传wordjson配置在ueditor\php\config.json中新增如下配置:     /*......
  • 编程打卡:C语言趣味编程习题做
    编程打卡:C语言趣味编程习题做数制转换问题描述给定一个M进制的数x,实现对x向任意非M进制的数的转换。设计思路输入M进制的数x,将x转换为十进制数,再将十进制数转换为任意非M进制的数。流程图graphA["开始"]-->B["输入M进制的数x"]-->C["将x转换为十进制数"]-->D["将十进......
  • 2-211-(LeetCode-470) 用 Rand7() 实现 Rand10()
     1.题目 https://leetcode.cn/problems/implement-rand10-using-rand7/submissions/425373186/ 2.解法 classSolutionextendsSolBase{publicintrand10(){inttemp=40;while(temp>=40){temp=(rand7()-1)*7......
  • CF1646E Power Board 题解
    题目链接:https://codeforces.com/contest/1646/problem/E题目大意:有一个\(n\timesm\)的矩阵,其中第\(i\)行第\(j\)列的格子中的数字是\(i^j\)。问:矩阵中存在多少个不同的数?解题思路:可以很明显地发现,第\(1\)行的数字全部都是\(1\),而且在其它行不会出现数值为\(1\)......