6

それぞれ 1000 以上のレコードを含む大量のバイナリ ファイルの読み取りを開始しようとしています。新しいファイルが常に追加されるので、ディレクトリを監視し、新しいファイルを受信したときに処理する Windows サービスを作成しています。ファイルは c++ プログラムで作成されました。C# で構造体定義を再作成し、データを正常に読み取ることができましたが、この方法では最終的にアプリケーションが強制終了されるのではないかと心配しています。

using (BinaryReader br = new BinaryReader(File.Open("myfile.bin", FileMode.Open)))
{
    long pos = 0L;
    long length = br.BaseStream.Length;

    CPP_STRUCT_DEF record;
    byte[] buffer = new byte[Marshal.SizeOf(typeof(CPP_STRUCT_DEF))];
    GCHandle pin;

    while (pos < length)
    {
        buffer = br.ReadBytes(buffer.Length);
        pin = GCHandle.Alloc(buffer, GCHandleType.Pinned);
        record = (CPP_STRUCT_DEF)Marshal.PtrToStructure(pin.AddrOfPinnedObject(), typeof(CPP_STRUCT_DEF));
        pin.Free();

        pos += buffer.Length;

        /* Do stuff with my record */
    }
}

実際には C++ アプリと通信していないため、GCHandle を使用する必要はないと思います。すべてがマネージ コードから行われていますが、別の方法を知りません。

4

6 に答える 6

8

使用Marshal.PtrToStructureはかなり遅いです。バイナリデータを読み取るさまざまな方法を比較 (およびベンチマーク) している CodeProject に関する次の記事が非常に役立ちました。

C# によるバイナリ ファイルの高速読み取り

于 2009-05-18T14:43:39.683 に答える
6

特定のアプリケーションについて、決定的な答えが得られるのは 1 つだけです。プロファイルを作成することです。

これは、大規模な PInvoke ソリューションを扱っているときに学んだ教訓です。データをマーシャリングする最も効果的な方法は、blittable なフィールドをマーシャリングすることです。つまり、CLR は、ネイティブ コードとマネージ コードの間でデータを移動するために memcpy に相当することを簡単に行うことができます。簡単に言えば、構造体からすべての非インライン配列と文字列を取得します。それらがネイティブ構造に存在する場合は、それらを IntPtr で表し、必要に応じて値をマネージ コードにマーシャリングします。

Marshal.PtrToStructure を使用する場合と、ネイティブ API で値を逆参照する場合の違いをプロファイルしたことはありません。これはおそらく、プロファイリングによって PtrToStructure がボトルネックとして明らかになった場合に投資すべきものです。

大規模な階層の場合、オンデマンドでマーシャリングするのではなく、構造全体をマネージド コードに一度にプルします。大きなツリー構造を扱うとき、私はこの問題に最も遭遇しました。個々のノードのマーシャリングは、それが blittable であり、その時点で必要なものだけをマーシャリングすることでパフォーマンスが向上する場合、非常に高速です。

于 2009-05-18T14:42:46.487 に答える
1

これはあなたの質問の範囲外かもしれませんが、fread() を実行するマネージド C++ で小さなアセンブリを作成するか、構造体で同様に高速に読み取ることができます。それらを読み込んだら、C# を使用して必要なすべての操作を行うことができます。

于 2009-05-18T14:43:53.987 に答える
0

これは、C++ やマーシャリングとは何の関係もないようです。あなたは他に何が必要なのか構造を知っています。

明らかに、1 つの構造体を表すバイトのグループを読み取り、BitConverter を使用してバイトを対応する C# フィールドに配置する単純なコードが必要です。

于 2013-03-31T18:45:55.483 に答える
0

これは、構造化ファイルで遊んでいるときに作成した小さなクラスです。これは、危険にさらされることを恥ずかしがっていた当時、私が見つけた最速の方法でした(これは、私が交換して同等のパフォーマンスを維持しようとしていたものでした.)

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;

namespace PersonalUse.IO {

    public sealed class RecordReader<T> : IDisposable, IEnumerable<T> where T : new() {

        const int DEFAULT_STREAM_BUFFER_SIZE = 2 << 16; // default stream buffer (64k)
        const int DEFAULT_RECORD_BUFFER_SIZE = 100; // default record buffer (100 records)

        readonly long _fileSize; // size of the underlying file
        readonly int _recordSize; // size of the record structure
        byte[] _buffer; // the buffer itself, [record buffer size] * _recordSize
        FileStream _fs;

        T[] _structBuffer;
        GCHandle _h; // handle/pinned pointer to _structBuffer 

        int _recordsInBuffer; // how many records are in the buffer
        int _bufferIndex; // the index of the current record in the buffer
        long _recordPosition; // position of the record in the file

        /// <overloads>Initializes a new instance of the <see cref="RecordReader{T}"/> class.</overloads>
        /// <summary>
        /// Initializes a new instance of the <see cref="RecordReader{T}"/> class.
        /// </summary>
        /// <param name="filename">filename to be read</param>
        public RecordReader(string filename) : this(filename, DEFAULT_STREAM_BUFFER_SIZE, DEFAULT_RECORD_BUFFER_SIZE) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="RecordReader{T}"/> class.
        /// </summary>
        /// <param name="filename">filename to be read</param>
        /// <param name="streamBufferSize">buffer size for the underlying <see cref="FileStream"/>, in bytes.</param>
        public RecordReader(string filename, int streamBufferSize) : this(filename, streamBufferSize, DEFAULT_RECORD_BUFFER_SIZE) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="RecordReader{T}"/> class.
        /// </summary>
        /// <param name="filename">filename to be read</param>
        /// <param name="streamBufferSize">buffer size for the underlying <see cref="FileStream"/>, in bytes.</param>
        /// <param name="recordBufferSize">size of record buffer, in records.</param>
        public RecordReader(string filename, int streamBufferSize, int recordBufferSize) {
            _fileSize = new FileInfo(filename).Length;
            _recordSize = Marshal.SizeOf(typeof(T));
            _buffer = new byte[recordBufferSize * _recordSize];
            _fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None, streamBufferSize, FileOptions.SequentialScan);

            _structBuffer = new T[recordBufferSize];
            _h = GCHandle.Alloc(_structBuffer, GCHandleType.Pinned);

            FillBuffer();
        }

        // fill the buffer, reset position
        void FillBuffer() {
            int bytes = _fs.Read(_buffer, 0, _buffer.Length);
            Marshal.Copy(_buffer, 0, _h.AddrOfPinnedObject(), _buffer.Length);
            _recordsInBuffer = bytes / _recordSize;
            _bufferIndex = 0;
        }

        /// <summary>
        /// Read a record
        /// </summary>
        /// <returns>a record of type T</returns>
        public T Read() {
            if(_recordsInBuffer == 0)
                return new T(); //EOF
            if(_bufferIndex < _recordsInBuffer) {
                // update positional info
                _recordPosition++;
                return _structBuffer[_bufferIndex++];
            } else {
                // refill the buffer
                FillBuffer();
                return Read();
            }
        }

        /// <summary>
        /// Advances the record position without reading.
        /// </summary>
        public void Next() {
            if(_recordsInBuffer == 0)
                return; // EOF
            else if(_bufferIndex < _recordsInBuffer) {
                _bufferIndex++;
                _recordPosition++;
            } else {
                FillBuffer();
                Next();
            }
        }

        public long FileSize {
            get { return _fileSize; }
        }

        public long FilePosition {
            get { return _recordSize * _recordPosition; }
        }

        public long RecordSize {
            get { return _recordSize; }
        }

        public long RecordPosition {
            get { return _recordPosition; }
        }

        public bool EOF {
            get { return _recordsInBuffer == 0; }
        }

        public void Close() {
            Dispose(true);
        }

        void Dispose(bool disposing) {
            try {
                if(disposing && _fs != null) {
                    _fs.Close();
                }
            } finally {
                if(_fs != null) {
                    _fs = null;
                    _buffer = null;
                    _recordPosition = 0;
                    _bufferIndex = 0;
                    _recordsInBuffer = 0;
                }
                if(_h.IsAllocated) {
                    _h.Free();
                    _structBuffer = null;
                }
            }
        }

        #region IDisposable Members

        public void Dispose() {
            Dispose(true);
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator() {
            while(_recordsInBuffer != 0) {
                yield return Read();
            }
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        #endregion

    } // end class

} // end namespace

使用する:

using(RecordReader<CPP_STRUCT_DEF> reader = new RecordReader<CPP_STRUCT_DEF>(path)) {
    foreach(CPP_STRUCT_DEF record in reader) {
        // do stuff
    }
}

(ここではかなり新しいです。投稿するには多すぎないことを願っています...クラスに貼り付けただけで、コメントなどを切り捨てて短くすることはありませんでした。)

于 2009-05-21T05:41:05.767 に答える