从 LPCWSTR 转换为 LPCSTR

Cha*_*Ray 1 .net c++ winapi

我在尝试将 LPCWSTR 转换为 LPCSTR 时遇到问题。

一些背景

我正在编写 VC++ 2010 应用程序,并且已经遇到了必须将 System::String^ 类型转换为 std::string 的情况。我使用此代码来执行此操作:

private: std::string toss(System::String^ s)
    {
        msclr::interop::marshal_context context;
        return context.marshal_as<std::string>(s);
    }
Run Code Online (Sandbox Code Playgroud)

这样做,我想我会解决我所有的问题。我错了。由此,我需要将 std::string 转换为 LPCSTR,以与某些 Windows API 一起使用。

在阅读了一些关于 SO 的现有问题后,我觉得我被卡住了。我被告知使用:

LPCSTR str = existingstr.c_str();
Run Code Online (Sandbox Code Playgroud)

但是,当我使用它时,出现错误:无法从 LPCWSTR 转换为 LPCSTR

有没有人更好地了解在这种特定情况下我应该做什么,或者我如何从 LPCWSTR 转换为 LPCSTR?

提前致谢。

AJ *_* S. 5

在 wchar 和基于字符的字符串之间来回转换时,我使用以下两个例程:

include <string>      // std::string, std::wstring
include <algorithm>   // std::copy  

std::wstring StringToWString(const std::string& s)  
{  
    std::wstring temp(s.length(),L' ');  
    std::copy(s.begin(), s.end(), temp.begin());  
    return temp;  
}  


std::string WStringToString(const std::wstring& s)  
{  
    std::string temp(s.length(), ' ');  
    std::copy(s.begin(), s.end(), temp.begin());  
    return temp;  
}  
Run Code Online (Sandbox Code Playgroud)

您现在可以通过以下假设 'existingstr' 是宽字符字符串来解决您的问题:

std::string narrow_str(WStringToString(existingstr));  

LPCSTR win_str = narrow_str.c_str();  
Run Code Online (Sandbox Code Playgroud)

给定一些“narrowstr”,您可以轻松地走另一条路:

std::wstring wide_str(StringToWString(narrowstr));  

LPWCSTR win_wstr = wide_str.c_str();  
Run Code Online (Sandbox Code Playgroud)

显然,这效率不高,因为您既要分配一个本地对象,又要通过堆栈将其复制回(我通过使用构造函数初始化而不是赋值来缓解这种情况……一些编译器以这种方式优化掉了额外的副本)。

如果可能,最好通过使用 UNICODE 宏来使用适当版本的 Windows API(请参阅http://msdn.microsoft.com/en-us/library/ff381407%28v=vs.85%29。 aspx - 使用字符串(Windows))。

但是,假设由于兼容性原因而无法实现,它确实让您对需要发生的事情有一些了解。