当使用C++/CLI包装C++本地代码时,常常需要将System::String转换为std::string或者char*以调用native C++函数。.net环境中的字符串是unicode的,占2个字节,而很多native C++函数都没有考虑unicode,这种转换不仅仅是2字节转1字节,同时也涉及到字符集的转换。
#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;
}