您不需要该方法:
string str = "hello".Substring(0, 2); // force not to inline the string
// it would be the same if it was inlined
GCHandle h = GCHandle.Alloc(str, GCHandleType.Pinned);
IntPtr ptr = h.AddrOfPinnedObject(); // Your address
// ch is h
// the unchecked is necessary (technically optional because it's default)
// because Marshal.ReadInt16 reads a signed Int16, while char is more similar
// to an unsigned Int16
char ch = unchecked((char)Marshal.ReadInt16(ptr));
或带有一些不安全的代码(请参阅固定语句):
fixed (char* ptr2 = str)
{
char ch2 = *ptr2;
}
如果你真的想要呢 PtrToStringChars(...)
?你不能拥有它......它直接在vcclr.h
标题中定义为内联函数(在我的第 37-39 行用于注释,40-48 用于代码)。