问题描述
目标是避免在需要 const wchar_t *
时复制字符串数据。
The goal is to avoid copying the string data when I need a const wchar_t*
.
答案似乎是,但是函数没有自己的MSDN条目(KB和博客中仅作为技巧提到)。那使我感到怀疑,我想和你们一起检查。
The answer seems to be yes, but the function PtrToStringChars
doesn't have its own MSDN entry (it's only mentioned in the KB and blogs as a trick). That made me suspicious and I want to check with you guys. Is it safe to use that function?
推荐答案
是的,没问题。它实际上是,但很难找。 C ++库的MSDN文档不是很好。它返回一个内部指针,该指针尚不适合转换为const wchar_t *。您必须固定指针,以使垃圾回收器无法移动字符串。使用pin_ptr<>来做到这一点。
Yes, no problem. It is actually somewhat documented but hard to find. The MSDN docs for the C++ libraries aren't great. It returns an interior pointer, that's not suitable for conversion to a const wchar_t* yet. You have to pin the pointer so the garbage collector cannot move the string. Use pin_ptr<> to do that.
您可以使用Marshal :: StringToHGlobalUni()创建字符串的副本。如果wchar_t *需要长时间保持有效,请改用该命令。将对象固定太长时间对于垃圾收集器来说不是很健康。
You can use Marshal::StringToHGlobalUni() to create a copy of the string. Use that instead if the wchar_t* needs to stay valid for an extended period of time. Pinning objects too long isn't very healthy for the garbage collector.
这篇关于是否可以在C ++ / CLI中获得指向String ^的内部数组的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!