2013-01-11 3 views
3

하나의 호출에서 이진 파일의 구조체 배열을 읽을 수 있습니까?이진 파일에서 구조체 배열의 빠른 읽기

struct Vector3 { float x, y, z; }

내가 C++ 코드를 C#을 포트가 필요합니다 :

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

답변

5

여기 방법 (약간의) 하나

예를 들어, 나는 정점의 수천을 포함하는 파일을 가지고 :

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; 
} 
+0

감사 (9 이상 이동합니다) – Newbee

1

예, 가능하지만, e 구조체를 사용하여 구조체에 패딩이 없도록 메모리에 매핑되는 방식을 정확하게 지정해야합니다.

자주 데이터를 직접 변환하는 것이 더 쉽습니다. 대부분의 처리 시간은 파일에서 데이터를 읽는 것이므로 데이터를 변환하는 오버 헤드가 적습니다. 예 :

byte[] bytes = File.ReadAllBytes(fileName); 
Vector3[] data = new Vector3[bytes.Length/12]; 
for (var i = 0; i < data.Length; i++) { 
    Vector3 item; 
    item.x = BitConverter.ToSingle(bytes, i * 12); 
    item.y = BitConverter.ToSingle(bytes, i * 12 + 4); 
    item.z = BitConverter.ToSingle(bytes, i * 12 + 8); 
    data[i] = item; 
} 
+0

당신이 팩의 크기 변경에 대해 걱정할 필요가 없습니다 부동의 정렬 화 된 사이즈, 4 있지만, 일반적으로 사실. – JerKimball

관련 문제