0

OpenFileDialog 返回一个指向内存的指针,该指针包含一系列以 null 结尾的字符串,后跟 final 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 回答