从LPCWSTR转换为LPCSTR [英] Converting from LPCWSTR to LPCSTR

查看:2024
本文介绍了从LPCWSTR转换为LPCSTR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有麻烦试图施放一个LPCWSTR到一个LPCSTR。

I'm having trouble trying to cast a LPCWSTR to an LPCSTR.

的背景

我编程一个VC ++ 2010应用程序,并已运行到哪里,我不得不从式系统转换的情况::字符串^到std :: string的。我用这个code这样做的:

I am programming a VC++ 2010 application, and have already run into the situation where I had to convert from type System::String^ to std::string. I used this code to do so:

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

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

Doing so, I thought I would solve all my problems. I was wrong. From this, I need to cast a std::string as an LPCSTR, to use with some Windows API.

读了一些存在的问题上做之后,我觉得我卡住了。我被告知使用方法:

After reading some of the existing questions on SO, I feel like I am stuck. I was told to use:

LPCSTR str = existingstr.c_str();

当我用这个,但我给出的错误:无法从LPCWSTR转换为LPCSTR

When I use this, however, I am given the error: Cannot convert from LPCWSTR to LPCSTR

有没有人有一个更好的主意是我应该做的这种特殊情况下,或如何,我可以从LPCWSTR转换为LPCSTR?

Does anyone have a better idea of what I should do in this specific case, or how I can convert from LPCWSTR to LPCSTR?

在此先感谢。

推荐答案

编辑:完全误解了问题,所以不顾我前面的回答,抱歉。如果你需要这个字符串后面传递到一个Windows API,你有充分的理由使用std :: string的,而不是标准:: wstring的?

completely misread the question so disregard my earlier answer, sorry. If you need to later pass this string into a Windows API, do you have a reason for using std::string and not std::wstring?

其他编辑:有在这里我而言有些混乱。什么是existingstr的类型,什么是Windows API函数你打电话的签名?我认为,这将有助于明确的东西。如果existingstr为std :: string的,然后.cstr()是LPCSTR兼容(即字符常量*)。如果existingstr为std :: wstring的,事实并非如此。是API以LPCSTR或LPCWSTR?

Additional edit: there's some confusion on my part here. What is the type of existingstr and what is the signature of the Windows API function you're calling? I think that would help clear things up. If existingstr is std::string, then .cstr() is compatible with LPCSTR (i.e. char const*). If existingstr is std::wstring, it is not. Is the API taking LPCSTR or LPCWSTR?

您可以用这个来代替:

private: std::wstring toss(System::String^ s)
{
   std::wstring result;
   {
       pin_ptr<wchar_t const> ptr = PtrToStringChars(s);
       result = ptr;
   }
   return result;
}

.c_str()在一个std :: wstring的会导致在wchar_t常量*(即LPCWSTR)。

.c_str() on a std::wstring would result in a wchar_t const* (i.e. a LPCWSTR).

这篇关于从LPCWSTR转换为LPCSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆