gpt4 book ai didi

.net - 从 LPCWSTR 转换为 LPCSTR

转载 作者:行者123 更新时间:2023-11-30 00:59:01 42 4
gpt4 key购买 nike

我在尝试将 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);
}

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

看了一些关于SO的现成问题,感觉卡住了。我被告知使用:

LPCSTR str = existingstr.c_str();

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

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

提前致谢。

最佳答案

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

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;
}

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

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

LPCSTR win_str = narrow_str.c_str();

给定一些 'narrowstr',你可以轻松地走另一条路:

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

LPWCSTR win_wstr = wide_str.c_str();

很明显,这是不高效的,因为你们都在分配一个局部变量,然后通过堆栈将其复制回来(我通过使用构造函数初始化而不是赋值来减轻一点......一些编译器优化掉了额外的拷贝方式)。

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

但是,假设出于兼容性原因这是不可能的,它确实可以让您了解需要发生什么。

关于.net - 从 LPCWSTR 转换为 LPCSTR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5112633/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com