gpt4 book ai didi

c# - 从二进制文件中快速读取结构数组

转载 作者:行者123 更新时间:2023-11-30 14:34:17 30 4
gpt4 key购买 nike

是否可以在一次调用中从二进制文件中读取一组结构?

例如,我有一个包含数千个顶点的文件:

struct Vector3 { float x, y, z; }

我需要 C# 端口用于 C++ 代码:

Vector3 *verts = new Vector3[num_verts];
fread ( verts, sizeof(Vector3), num_verts, f );

最佳答案

这是(几种)方法之一:

void Main()
{
var pts =
(from x in Enumerable.Range(0, 10)
from y in Enumerable.Range(0, 10)
from z in Enumerable.Range(0, 10)
select new Vector3(){X = x, Y = y, Z = z}).ToArray();

// write it out...
var bigAssByteArray = new byte[Marshal.SizeOf(typeof(Vector3)) * pts.Length];
var pinnedHandle = GCHandle.Alloc(pts, GCHandleType.Pinned);
Marshal.Copy(pinnedHandle.AddrOfPinnedObject(), bigAssByteArray, 0, bigAssByteArray.Length);
pinnedHandle.Free();
File.WriteAllBytes(@"c:\temp\vectors.out", bigAssByteArray);

// ok, read it back...
var readBytes = File.ReadAllBytes(@"c:\temp\vectors.out");
var numVectors = readBytes.Length / Marshal.SizeOf(typeof(Vector3));
var readVectors = new Vector3[numVectors];
pinnedHandle = GCHandle.Alloc(readVectors, GCHandleType.Pinned);
Marshal.Copy(readBytes, 0, pinnedHandle.AddrOfPinnedObject(), readBytes.Length);
pinnedHandle.Free();

var allEqual =
pts.Zip(readVectors,
(v1,v2) => (v1.X == v2.X) && (v1.Y == v2.Y) && (v1.Z == v2.Z))
.All(p => p);
Console.WriteLine("pts == readVectors? {0}", allEqual);
}


struct Vector3
{
public float X;
public float Y;
public float Z;
}

关于c# - 从二进制文件中快速读取结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14269568/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com