Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 764
user541686 Avatar asked Nov 14 '22 19:11

user541686


1 Answers

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

like image 146
Lorenzo Dematté Avatar answered Nov 24 '22 00:11

Lorenzo Dematté