c# string与c++ std::string的互相转换

本文介绍了如何在C++/CLI中进行System::String^与std::string之间的转换,这对于使用C++/CLI包装C++本地代码并调用不支持Unicode的C++函数时非常有用。示例代码展示了如何通过msclr库的marshal_as函数完成转换,并打印转换后的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文转载自:C#DLL托管c++ (CLI) String^ 到 std::string 的相互转化_成魔的羔羊的博客-CSDN博客

当使用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;  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值