从 System.String 转换为 PCTSTR [英] convert from System.String to PCTSTR
问题描述
我必须将 System.String (C#) 转换为 PCTSTR,该 PCTSTR 将被键入为 _nullterminated const char*
I'm having to convert from System.String (C#) into a PCTSTR which would be typed as _nullterminated const char*
到目前为止,我找不到任何可以确切告诉我如何执行此操作的信息.
So far I can't find anything that can tell me exactly how to do this.
从 System::String (C++/CLI) 转换的大量示例,但我在 System.String (C#) 上找不到任何内容
Plenty of examples to convert from System::String (C++/CLI), but I can't find anything on System.String (C#)
我在 Visual Studio 2005 中工作.
I'm working in Visual Studio 2005.
推荐答案
当 PCTSTR
是 const char*
的 typedef 时,使用 Marshal.StringToHGlobalAnsi.
When PCTSTR
is a typedef for const char*
, use Marshal.StringToHGlobalAnsi.
当 PCTSTR
是 const wchar_t*
的 typedef 时,使用 Marshal.StringToHGlobalUni.
When PCTSTR
is a typedef for const wchar_t*
, use Marshal.StringToHGlobalUni.
在这两种情况下,调用 Marshal.FreeHGlobal 完成后释放内存;尽管您使用 C#,但有问题的内存分配是非托管的,因此不符合垃圾收集条件,并且如果您不正确清理它会泄漏.
In both cases, call Marshal.FreeHGlobal to free the memory when you're done with it; despite your using C#, the memory allocation in question is unmanaged, so consequently is not eligible for garbage collection and will leak if you don't clean it up properly.
这篇关于从 System.String 转换为 PCTSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!