如何在在Visual C++ .NET 中將System::String* 转换为 Char*

方法 1

PtrToStringChars 提供您實際 String 物件的內部指標。如果要將這個指標傳送到 Unmanaged 函式呼叫,您必須先將指標固定起來,以確保物件不會在非同步記憶體回收處理期間移動:
//#include <vcclr.h>
System::String * str = S"Hello world\n";
const __wchar_t __pin * str1 = PtrToStringChars(str);
wprintf(str1);					

方法 2

StringToHGlobalAnsi 會將 Managed String 物件的內容複製到原始堆積中,然後直接轉換為美國國家標準局 (ANSI,American National Standards Institute) 格式。這個方法會配置必要的原始堆積記憶體:
//using namespace System::Runtime::InteropServices;
System::String * str = S"Hello world\n";
char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
printf(str2);
Marshal::FreeHGlobal(str2);

方法 3

VC7 CString 类具有取得 Managed String 指针并将 CString 和內容一起載入的建構函式:
//#include <atlstr.h>
System::String * str = S"Hello world\n";
CString str3(str);
printf(str3);

完整样例:

//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;
}

转载于:https://www.cnblogs.com/suiyingjie/archive/2007/03/29/693277.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值