在 Visual C++ .NET 中从 System::String* 转换为 Char* 或者 CString
2010-01-17 17:45
399 查看
本文介绍使用 Visual C++ .NET 中的托管扩展从 System::String* 转换为 char* 的若干方法。
[/code]
[/code]
[/code]
[/code]
方法 1
PtrToStringChars 指定了一个指向实际 String 对象的内部指针。如果将此指针传递给非托管函数调用,则必须先锁定该指针,以确保在进行异步垃圾回收过程中对象不会移动:[code]//#include <vcclr.h> System::String * str = S"Hello world/n"; const __wchar_t __pin * str1 = PtrToStringChars(str); wprintf(str1);
[/code]
方法 2
StringToHGlobalAnsi 将托管 String 对象的内容复制到本机堆,然后动态地将它转换为美国国家标准学会 (ANSI) 格式。此方法将分配所需的本机堆内存:[code]//using namespace System::Runtime::InteropServices; System::String * str = S"Hello world/n"; char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str); printf(str2); Marshal::FreeHGlobal(str2);
[/code]
方法 3
VC7 CString 类有一个构造函数,它带有一个托管 String 指针并将其内容加载到 CString 中:[code]//#include <atlstr.h> System::String * str = S"Hello world/n"; CString str3(str); printf(str3);
[/code]
完整代码示例
[code]//compiler option:cl /clr #include <vcclr.h> #include <atlstr.h> #include <stdio.h> #using <mscorlib.dll> using namespace System; using namespace System::Runtime::InteropServices; int _tmain(void) { System::String * str = S"Hello world/n"; //method 1 const __wchar_t __pin * str1 = PtrToStringChars(str); wprintf(str1); //method 2 char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str); printf(str2); Marshal::FreeHGlobal(str2); //method 3 CString str3(str); printf(str3); return 0; }
原文地址: http://support.microsoft.com/?id=311259
[/code]
相关文章推荐
- HOW TO:在 Visual C++ .NET 中从 System::String* 转换为 Char*
- HOW TO:在 Visual C++ .NET 中从 System::String* 转换为 Char*
- Visual C++ .NET 中从 System::String* 转换为 Char*
- 如何在在Visual C++ .NET 中將System::String* 转换为 Char*
- 在 Visual C++ .NET 中从 System::String* 转换为 Char*
- HOW TO:在 Visual C++ .NET 中从 System::String* 转换为 Char*
- 收集的关于C++中CString,int,string,char*,string之间的转换
- Visual C++ .NET 中 System::String^ 和 char * 互转
- C++中 char*, string, CString, int, double之间相互的转换
- c++中的一些类型转换 : CString,string,int ,long,double,char*,const char*,date等
- c++中的一些类型转换 : CString,string,int ,long,double,char*,const char*,date等
- c++中的一些类型转换 : CString,string,int ,long,double,char*,const char*,date等----留着备用
- c++中的一些类型转换 : CString,string,int ,long,double,char*,const char*,date
- Visual C++ .NET 中 System::String^ 和 char * 互转
- 在C++.NET中,System::String^与char*相互转换
- c++中的一些类型转换 : CString,string,int ,long,double,char*,const char*,date等 .
- C++ 中 int,char*,string,CString之间相互转换-整理
- C++实现CString和string的互相转换
- MFC/C++/C中CString, int, string, char*之间的转换
- C++ int,char,string,CString类型转换 [转]