首页 > 代码库 > 托管c++ (CLI) String^ 到 std::string 的相互转化

托管c++ (CLI) String^ 到 std::string 的相互转化

#include "stdafx.h"
#include <string>
#include <msclr\marshal_cppstd.h>
#include <iostream>

using namespace msclr::interop;
using namespace System;

int main(array<System::String ^> ^args)
{
	// 为了可以打印wstring到控制台
	std::wcout.imbue(std::locale("chs"));

	// 声明两个string
	std::string strOld = "阿里路亚!"; //std的string
	String^ strNew = "耶稣基督!"; //cli的string.

	//std::string转cli的string
	String^ stdToCli = marshal_as<String^>(strOld);
	Console::WriteLine(stdToCli);

	//cli的string转std::string
	std::string cliToStd = marshal_as<std::string>(strNew);
	std::cout << cliToStd << std::endl;

	//cli的string转std::wstring
	std::wstring cliToWstring = marshal_as<std::wstring>(strNew);
	std::wcout << cliToWstring << std::endl;
}