从PInvoked OpenFileDialog(GetOpenFileName)编组非托管数组的字符串

时间:2009-03-20 17:00:34

标签: c# windows pinvoke marshalling openfiledialog

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

1 个答案:

答案 0 :(得分:1)

你正在做的事情看起来很不错 - 我唯一要做的改变就是使用Encoding.Unicode.GetByteCount(name)而不是name.Length * 2(这更加明显是什么)。

此外,如果您肯定您的非托管数据是Unicode,则可能需要使用Marshal.PtrToStringUni(ptr),因为它消除了有关字符串编码的任何歧义。