Visual C++ .NET 中 System::String^ 和 char * 互转



原文链接:http://blog.csdn.net/qq506124204/article/details/8969490


使用 Visual C++ .NET 中的托管扩展从 System::String^ 转换为 char* 的若干方法。 

方法 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 <span style="background-color: rgb(245, 245, 245);">^</span><span style="background-color: rgb(245, 245, 245);"> str = "Hello world\n";</span>
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";<span style="white-space: pre;">	</span>

    //method 1
    char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
    printf(str2);
    Marshal::FreeHGlobal( IntPtr(str2) );
    //method 2
    CString str3(str); 
    printf(str3);
<pre class="code" style="padding: 10px; width: auto; color: rgb(51, 51, 51); font-family: Consolas,'Courier New',Courier,monospace; font-size: 13px; margin-top: 0px; margin-bottom: 0px; position: relative;" name="code">  const char * p = "你妹的";
  String ^ MyStr = Marshal::PtrToStringAnsi((IntPtr)(char *)p);
  Console::WriteLine(MyStr);
return 0;}
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值