.NET Marshal.PtrToStringUni(IntPtr) vs. new String(char*)
What's the difference between new String(char*)
and Marshal.PtrToStringUni(IntPtr)
, aside from the obvious fact that one takes char*
and one takes IntPtr
? When should I use which?
I remember getting a really ra开发者_运维百科ndom access violation that took an enormous amount of time to track down about a couple of years ago when using the constructor, and it went away when I used the PtrToStringUni
. Maybe that wasn't the real cause, I don't know, but it seemed to be.
I never figured out what the difference was, though. Any ideas?
Edit:
This question has the answer to most of my question; however: is there any explanation for my access violation, or was it because of something else?
Based on the linked answer, I can guess that you didn't pin the pointer to the char*, which caused (at random) to have the GC move the char* while the constructor was still running, causing the access violation. Just a guess :)
The difference is that you can't use pointers without dropping into unsafe code. char* is an actual pointer. IntPtr wraps a pointer.
From the msdn you linked:
"If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation."
Is your char[] null-terminated?
精彩评论