0

OpenFileDialog は、null で終わる文字列のシーケンスを含むメモリへのポインターを返し、その後に配列の末尾を示す最後の null が続きます。

これは、アンマネージ ポインターから C# 文字列を取得する方法ですが、より安全でエレガントな方法があるはずです。

            IntPtr unmanagedPtr = // start of the array ...
            int offset = 0;
            while (true)
            {
                IntPtr ptr = new IntPtr( unmanagedPtr.ToInt32() + offset );
                string name = Marshal.PtrToStringAuto(ptr);
                if(string.IsNullOrEmpty(name))
                    break;

                // Hack!  (assumes 2 bytes per string character + terminal null)
                offset += name.Length * 2 + 2;
            }
4

1 に答える 1

1

あなたがやっていることはかなり良さそうです - 私が行う唯一の変更は、Encoding.Unicode.GetByteCount(name)代わりに使用することですname.Length * 2(何が起こっているのかがより明白になります)。

また、Marshal.PtrToStringUni(ptr)管理されていないデータが Unicode であることが確実な場合は、文字列エンコーディングに関するあいまいさがなくなるため、使用することをお勧めします。

于 2009-03-20T17:29:44.213 に答える