最近一直在研究
沒有想到在C#中竟沒有直接的指令
在C#中結構體是一個比較復雜的東西
通過使用屬性可以自定義結構在內存中的布局方式
[System
struct TestUnion
{
[System
public int i;
[System
public double d;
[System
public char c;
[System
public byte b;
}
在上一個代碼段中
以下是字段從其他顯式設置的位置開始的另一個示例
[System
struct TestExplicit
{
[System
public long lg;
[System
public int i
[System
public int i
[System
public double d;
[System
public char c;
[System
public byte b;
}
i
我做了一個簡單的測試程序
using System;
using System
using System
using System
using System
using System
using System
using System
using System
namespace RWFile
{
public partial class Form
{
public Form
{
InitializeComponent();
}
//從文件中讀結構體
private void button
{
string strFile = Application
if (!File
{
MessageBox
return;
}
FileStream fs = new FileStream(strFile
FileAccess
TestStruct ts = new TestStruct();
byte[] bytData = new byte[Marshal
fs
fs
ts = rawDeserialize(bytData);
textBox
textBox
textBox
}
//向文件中寫結構體
private void button
{
string strFile = Application
FileStream fs = new FileStream(strFile
FileAccess
TestStruct ts = new TestStruct();
ts
ts
ts
byte[] bytData = rawSerialize(ts);
fs
fs
}
[StructLayout(LayoutKind
public struct TestStruct
{
[MarshalAs(UnmanagedType
public double dTest;
[MarshalAs(UnmanagedType
public UInt
[MarshalAs(UnmanagedType
//
public byte[] bTest;
}
//序列化
public static byte[] rawSerialize(object obj)
{
int rawsize = Marshal
IntPtr buffer = Marshal
Marshal
byte[] rawdatas = new byte[rawsize];
Marshal
Marshal
return rawdatas;
}
//反序列化
public static TestStruct rawDeserialize(byte[] rawdatas)
{
Type anytype = typeof(TestStruct);
int rawsize = Marshal
if (rawsize > rawdatas
IntPtr buffer = Marshal
Marshal
object retobj = Marshal
Marshal
return (TestStruct)retobj;
}
}
}
From:http://tw.wingwit.com/Article/program/net/201311/12072.html