如何将结构体写入到文件中去?

lightingstorm 2006-11-09 03:28:10
C#下面,怎么把一个自定义的结构体写入到文件中去?
写进去之后,还要在C语言的平台去读取文件中的结构体信息,重构结构体。大家看看,怎么做?
我现在主要担心结构体在C#中输出到文件的格式与C的不一样,导致不兼容,不能正确读取信息。
...全文
814 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
mobydick 2006-11-09
  • 打赏
  • 举报
回复
注意不要使用http序列化,要用二进制序列化。
不然只有声明为public 的 字段才被保存。
yeerh 2006-11-09
  • 打赏
  • 举报
回复
二进制的序列化与反序列化


/// <summary>
/// 序列化
/// </summary>
/// <param name="data">要序列化的对象</param>
public static byte[] Serialize(object data)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream rems = new MemoryStream();
formatter.Serialize(rems, data);
return rems.GetBuffer();
}

/// <summary>
/// 反序列化
/// </summary>
/// <param name="data">数据缓冲区</param>
/// <returns>对象</returns>
public static object Deserialize(byte[] data)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream rems = new MemoryStream(data);
return formatter.Deserialize(rems);
}
lightingstorm 2006-11-09
  • 打赏
  • 举报
回复
我试过了liangxf0022(小新) 的做法
序列化的内容在文件中是有头部的
如果在C语言中提取出来的时候还要进行一些操作
不知道有没有兼容性更好的?

我再试试hdt(倦怠) 的建议
lzpsky 2006-11-09
  • 打赏
  • 举报
回复
[Serializable]首先让该结构体是可序列化,然后序列化后写入文件中
真相重于对错 2006-11-09
  • 打赏
  • 举报
回复
可以考虑用
[StructLayout(LayoutKind = LayoutKind.Explicit)]
struct yourstruct
{
[FieldOffset(0)] int n;
[FieldOffset(4)] int m;
}
yourstruct y1 = new ....
int size = Marshal.SizeOf( typeof(yorustruct) );
IntPtr ps = Marsha.AllocHGlobal(size);
Marshal.StructureToPtr( y1 , ps , true );
byte[] b = new byte[size];
for( int i=0 ; i<size ; i++ )
{
b[i] = Marshal.ReadByte( ps , i );
}
再把byte流写入文件
liangxf0022 2006-11-09
  • 打赏
  • 举报
回复
yeerh(边城浪)正确,MSDN上的例子

[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
The code example below shows how an instance of this class can be serialized to a file.
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
lightingstorm 2006-11-09
  • 打赏
  • 举报
回复

如果要写入文件该怎么调用?
yeerh 2006-11-09
  • 打赏
  • 举报
回复
将结构加上
[Serializable()]
特性即可序列化为二进制.
蓝色水 2006-11-09
  • 打赏
  • 举报
回复
好象c# 的真正结构体挺麻烦的

110,552

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧