Visual C++ .NET 中 System::String^ 和 char * 互转
2013-05-24 13:10
344 查看
使用 Visual C++ .NET 中的托管扩展从 System::String^ 转换为 char* 的若干方法。
StringToHGlobalAnsi 将托管 String 对象的内容复制到本机堆,然后动态地将它转换为美国国家标准学会
(ANSI) 格式。此方法将分配所需的本机堆内存:
VC7 CString 类有一个构造函数,它带有一个托管
String 指针并将其内容加载到 CString 中:
--------------------------------------- char * 转 String^ ------------------------
方法 1
StringToHGlobalAnsi 将托管 String 对象的内容复制到本机堆,然后动态地将它转换为美国国家标准学会(ANSI) 格式。此方法将分配所需的本机堆内存:
//using namespace System::Runtime::InteropServices; char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str); printf(str2); Marshal::FreeHGlobal( IntPtr(str2) );
方法2
VC7 CString 类有一个构造函数,它带有一个托管String 指针并将其内容加载到 CString 中:
//#include <atlstr.h> System::String ^ str = "Hello world\n"; CString str3( str ); printf(str3);
--------------------------------------- char * 转 String^ ------------------------
const char * p = "你妹的"; String ^ MyStr = Marshal::PtrToStringAnsi((IntPtr)(char *)p); Console::WriteLine(MyStr);
完整代码示例
//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 = "Hello world\n"; //method 1 char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str); printf(str2); Marshal::FreeHGlobal( IntPtr(str2) );
//method 2 CString str3(str); printf(str3);
const char * p = "你妹的"; String ^ MyStr = Marshal::PtrToStringAnsi((IntPtr)(char *)p); Console::WriteLine(MyStr);return 0;}
相关文章推荐
- Visual C++ .NET 中 System::String^ 和 char * 互转
- 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* 或者 CString
- HOW TO:在 Visual C++ .NET 中从 System::String* 转换为 Char*
- 在 Visual C++ .NET 中从 System::String* 转换为 Char*
- 如何在在Visual C++ .NET 中將System::String* 转换为 Char*
- 在VC++.net中将System::String __gc* 转换为本机的char *或wchar_t *的三种方法
- 在C++.NET中,System::String^与char*相互转换
- 官方水晶报表.NET 应用程序实例下载(C#、Visual C++.NET)
- 用Visual C++.NET实现XML解析
- 用Visual C++.NET进行GDI+编程
- Early Stages of the (Visual) C++ .Net 17
- Visual C++.NET编程讲座之四
- Visual C++.NET中的字符串转换方法(ZT)
- C++中string、char *、char[]的转换
- HOW TO:使用 ADO.NET 和 Visual C++ .NET 调用带参数的存储过程
- Visual C++.NET DirectShow编程
- Visual C++.net 基础讲座一