编组的从PInvoked的OpenFileDialog串的非托管阵列(GetOpenFileName)
-
21-08-2019 - |
题
的OpenFileDialog返回一个指针,指向包含空终止字符串的序列存储器,然后进行最终空以指示该阵列的端部。
这是如何我从非托管指针越来越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;
}
解决方案
你在做什么看起来很不错 - 我会做的唯一的变化是使用Encoding.Unicode.GetByteCount(name)
而不是name.Length * 2
(它只是更明显发生了什么)
此外,你可能想,如果你是积极的,非托管的数据是Unicode,因为它消除了你的字符串编码任何歧义使用Marshal.PtrToStringUni(ptr)
。
不隶属于 StackOverflow