【问题标题】:Marshalling an an unmanaged array of strings from a PInvoked OpenFileDialog (GetOpenFileName)从 PInvoked OpenFileDialog (GetOpenFileName) 编组一个非托管的字符串数组
【发布时间】:2009-03-20 17:00:33
【问题描述】:

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

【问题讨论】:

    标签: c# windows pinvoke marshalling openfiledialog


    【解决方案1】:

    您正在做的事情看起来不错 - 我要做的唯一更改是使用 Encoding.Unicode.GetByteCount(name) 而不是 name.Length * 2(发生的事情更明显)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      相关资源
      最近更新 更多