Routing an Unmanaged String Array from PInvoked OpenFileDialog (GetOpenFileName)

OpenFileDialog returns a pointer to memory containing a sequence of strings with a null terminating character, and then trailing null to indicate the end of the array.

This is how I return C # strings from an unmanaged pointer, but I'm sure there should 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;
            }
0
source share
1 answer

What you do looks pretty good - the only change I would make is to use Encoding.Unicode.GetByteCount(name)instead name.Length * 2(it's more obvious what is happening).

, Marshal.PtrToStringUni(ptr), , Unicode, .

+1

Source: https://habr.com/ru/post/1746493/


All Articles