使 C#.NET 中的 IntPtr 指向字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11090427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:26:30  来源:igfitidea点击:

make IntPtr in C#.NET point to string value

c#.netpointersinterop

提问by Saher Ahwal

I am using a class which has StringHandlefield which is an IntPtrvalue that represents a LPCWSTRin C++.

我正在使用一个具有StringHandle字段的类,该字段是在 C++IntPtr中表示 a的值 LPCWSTR

internal IntPtr StringHandle; // LPCWSTR

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

现在说我有一个字符串: 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 ?

如何使用 String 句柄指向 String 的开头,使其类似于 C++ LPCWSTR ?

采纳答案by Eren Ers?nmez

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

您需要先将字符串复制到非托管内存,然后IntPtr从该位置获取。你可以这样做:

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.

最好在尝试/最后完成所有这些。

回答by CodingGorilla

You want to use one of the StringTo* methods on the Marshalclass

你想使用StringTo之一*的方法Marshal

回答by Hans Passant

Managed strings movein 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().

当垃圾收集器压缩堆时,托管字符串在内存中移动。所以他们没有一个稳定的地址,也不能直接转换成 LPCWSTR。您需要使用 GCHandle.Alloc() 固定字符串以使用 GCHandle.AddrOfPinnedObject 或使用 Marshal.StringToHGlobalUni() 将其复制到非托管内存中。

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

如果地址需要稳定一段时间,强烈建议复制。