c# - 在 C# 中将字节读入结构

标签 c# file-io struct

是时候讨论另一个离奇的问题了。我正在为我的小型 3D 引擎项目编写 MD2 加载器。在我的旧语言 (C) 中,我可以定义一个结构,然后从一个打开的文件中直接将 read() 读取到该结构中。我有一个结构来保存来自 MD2 文件的头信息,如下所示:

[StructLayout(LayoutKind.Sequential)]
public struct MD2_Header
{
    public int FourCC;
    public int Version;
    public int TextureWidth;
    public int TextureHeight;
    public int FrameSizeInBytes;
    public int NbrTextures;
    public int NbrVertices;
    public int NbrTextureCoords;
    public int NbrTriangles;
    public int NbrOpenGLCmds;
    public int NbrFrames;
    public int TextureOffset;
    public int TexCoordOffset;
    public int TriangleOffset;
    public int FrameOffset;
    public int OpenGLCmdOffset;
    public int EndOffset;
}

在我的阅读器代码中,我想做类似的事情:

// Suck the MD2 header into a structure, it is 68 bytes long.
Classic.Util.MD2_Header md2hdr = new Classic.Util.MD2_Header();
md2hdr = reader.ReadBytes(sizeof(Classic.Util.MD2_Header));

我意识到这是不正确的,因为它有点奇怪地破坏了类型安全,但你明白我想要完成什么。我可以通过单独调用 reader.ReadInt32() 来做到这一点,但我很好奇是否有任何方法可以让它按照我想要的方式使用普通库调用来工作。

我已经稍微研究了 Marshal.Copy() 方法,但它似乎是为了在托管内存和非托管内存之间切换,这并不是我在这里所做的。

有什么建议吗?

最佳答案

将字节流读入字节数组,命名为packet,尝试如下:

GCHandle pinned = GCHandle.Alloc(packet, GCHandleType.Pinned);
MD2_Header h = (MD2_Header)Marshal.PtrToStructure(pinned.AddrOfPinnedObject(), typeof(MD2_Header));
pinned.Free();

关于c# - 在 C# 中将字节读入结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3249126/

相关文章:

java - 我需要一种优雅的方式来从处理中排除特定的单词

java - 在 Java 中逐行读取大型 JSON 文件的快速高效方法

c - 别名结构的习语

c# - 委托(delegate)如何指向方法?

c# - JSON反序列化将负值转换为绝对值

python - 可以在一个文件中存储多个数据结构以进行保存和加载(python)吗?

当我将参数定义为 struct * 时,编译器说参数是 struct ** 类型

c - 如何在 C 中实现位集

c# - Stateful Expression 访问者多次运行问题

c# - C# 中的匹配标签