5

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 random 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?

Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886

2 Answers2

1

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

Lorenzo Dematté
  • 7,638
  • 3
  • 37
  • 77
0

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?

hoodaticus
  • 3,772
  • 1
  • 18
  • 28
  • I thought that you weren't using unsafe, but apparently that constructor wouldn't even show up without it. Edited my answer. – hoodaticus Jul 22 '11 at 05:06