C2005中System::String转换为std::string

C#与C++字符串互转
本文介绍了一种在不使用Vcclr.h中的PtrToStringChars的情况下,将.NET Framework中的String类型转换为C++标准库中的std::string或std::wstring的方法。通过示例代码展示了如何利用Runtime::InteropServices命名空间中的Marshal类来完成这一转换。

http://msdn.microsoft.com/zh-cn/library/1b4az623%28VS.80%29.aspx

 

可以在不使用 Vcclr.h 中的 PtrToStringChars 的情况下将 String 转换为 std::stringstd::wstring

示例

// convert_system_string.cpp
// compile with: /clr
#include <string>
#include <iostream>
using namespace std;
using namespace System;

void MarshalString ( String ^ s, string& os ) {
using namespace Runtime::InteropServices;
const char* chars =
(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}

void MarshalString ( String ^ s, wstring& os ) {
using namespace Runtime::InteropServices;
const wchar_t* chars =
(const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}

int main() {
string a = "test";
wstring b = L"test2";
String ^ c = gcnew String("abcd");

cout << a << endl;
MarshalString(c, a);
c = "efgh";
MarshalString(c, b);
cout << a << endl;
wcout << b << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值