大家好:我用filestream里的read方法把一个文件读进了一个字节数组 。请问,我怎么才能把它读进一个结构体里,比如头两个字节是赋值给结构体的第一个成员,后两个给第二个成员,一直往下,
是需要序列化吗,谢谢大家!!
是需要序列化吗,谢谢大家!!
解决方案 »
- 看了那些项目我闷了。。。
- 托盘的鼠标移入移出事件?
- winform中如何把科学技术法转换成正常的数字显示
- winform窗体中的字体大小要怎么改啊?
- 如何打简码就能出值??谢谢大家了
- 2007年10月C#版务帖
- 关于listbox刷新问题!!
- 一个WEB系统(C#。NET),我想在打开登录页面时就检验某台电脑是否有权限访问本系统,能不能通过检验该客户端电脑上是否存在某文件,若存
- 如何实现图片的扭曲变换,比如正方形的图片变换为梯形.
- C#使用mysql数据库,列名去汉字别名出乱码问题
- ftp中如何获取远程主机文件的最后修改时间
- 如何将dataSet中的数据导入到Excel文件(*.xls)中???
再Marshal.PtrToStructure 将数据从非托管内存块封送到托管对象
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} public class StructSAM
{
public string First;
public string Second;
public string Third;
public string Nth;
public void sa()
{ }
} public void doThing()
{
byte[] byteTemp;
using (FileStream fs = new FileStream(@"C:\temp.jpg", FileMode.Open))
{
byteTemp = new byte[fs.Length];
fs.Read(byteTemp, 0, byteTemp.Length);
fs.Close();
} Type sam = typeof(StructSAM);
FieldInfo[] mInfo = sam.GetFields();
//MemberInfo[]
StructSAM s = new StructSAM(); int sourceIndex = 0;
for( int i = 0; i<mInfo.Length; i++ )
{
//MessageBox.Show(mInfo[i].Name);
byte[] bytTemp = new byte[5];
Array.Copy(byteTemp, sourceIndex, bytTemp, 0, 2);
mInfo[i].SetValue(s, System.Text.Encoding.Default.GetString(bytTemp));
sourceIndex += 2;
}
for (int i = 0; i < mInfo.Length; i++)
{
string strTemp = mInfo[i].GetValue(s).ToString();
MessageBox.Show(strTemp);
}
} private void button1_Click(object sender, EventArgs e)
{
doThing();
}
}
using System.IO;
using System.Reflection;
public class MainForm : System.Windows.Forms.Form
{
[DllImport("Kernel32.dll",EntryPoint="RtlMoveMemory")]
public static extern void CopyMemory (ref Test Source,IntPtr Destination,int Length); unsafe private void button1_Click(object sender, System.EventArgs e)
{
Test test = new Test();
char cTemp = 'A'; char * c = &cTemp;
IntPtr i = (IntPtr)c; CopyMemory(ref test, i, 2);
}
}[StructLayout(LayoutKind.Sequential)]
public struct Test
{
public char head;
}ps:如果你需要得到如数组等引用类型的指针,请使用fiexd关键字。
{
[DllImport("Kernel32.dll",EntryPoint="RtlMoveMemory")]
public static extern void CopyMemory (ref Test Source,IntPtr Destination,int Length); unsafe private void button1_Click(object sender, System.EventArgs e)
{
Test test = new Test();
byte[] bytes = System.Text.Encoding.Default.GetBytes("ABCDEFG"); fixed(byte* b = bytes)
{
IntPtr i = (IntPtr)b; CopyMemory(ref test, i, bytes.Length);
}
}
}[StructLayout(LayoutKind.Sequential)]
public struct Test
{
public char head1;
public char head2;
public char head3;
public char head4;
public char head5;
public char head6;
public char head7;
}
ps:最近问这个问题的人好多,楼主的QQ是"会飞的鱼丸"?