是否可以在C ++ / CLI中获得指向String ^的内部数组的指针? [英] Is it possible to get a pointer to String^'s internal array in C++/CLI?

查看:103
本文介绍了是否可以在C ++ / CLI中获得指向String ^的内部数组的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是避免在需要 const wchar_t * 时复制字符串数据。

The goal is to avoid copying the string data when I need a const wchar_t*.

答案似乎是,但是函数 PtrToStringChars 没有自己的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 ^的内部数组的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆