make IntPtr in C#.NET point to string value

冷暖自知 提交于 2020-01-01 04:01:07

问题


I am using a class which has StringHandle field which is an IntPtr value that represents a LPCWSTR in C++.

internal IntPtr StringHandle; // LPCWSTR

say now that I have a String: string x = "abcdefg"

How can I use the String handle to point to the beginning of the String so that it is like C++ LPCWSTR ?


回答1:


You need to copy the string to the unmanaged memory first and then get the IntPtr from that location. You can do so like:

IntPtr strPtr = Marshal.StringToHGlobalUni(x);

also, you need to make sure to free the unmanaged memory:

Marshal.FreeHGlobal(strPtr);

it's best to do all this in a try/finally.




回答2:


Managed strings move in memory when the garbage collector compacts the heap. So they don't have a stable address and can't directly be cast to a LPCWSTR. You'll need to either pin the string with GCHandle.Alloc() to use GCHandle.AddrOfPinnedObject or copy it into unmanaged memory with Marshal.StringToHGlobalUni().

Strongly prefer copying if the address needs to be stable for a while.




回答3:


You want to use one of the StringTo* methods on the Marshal class



来源:https://stackoverflow.com/questions/11090427/make-intptr-in-c-net-point-to-string-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!