views:

212

answers:

1

OpenFileDialog returns a pointer to memory containing a sequence of null-terminated strings, followed by final null to indicate the end of the array.

This is how I'm getting C# strings back from the unmanaged pointer, but I'm sure there must be a safer, more elegant way.

            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  A: 

What you're doing looks pretty good - the only change I would make would be to use Encoding.Unicode.GetByteCount(name) instead of name.Length * 2 (it's just more obvious what's going on).

Also, you might want to use Marshal.PtrToStringUni(ptr) if you are positive that your unmanaged data is Unicode, as it removes any ambiguity about your string encoding.

Mike