Windows上的C ++ std :: string转换问题 [英] C++ std::string conversion problem on Windows

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

问题描述

这是我的程序:

bool Open(std::string filename)
{
    ...
    HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
    ...
}

错误:"CreateFileW":无法将参数1从"const char *"转换为"LPCWSTR"指向的类型无关.转换需要reinterpret_cast,C样式强制转换或函数样式强制转换

Error:'CreateFileW' : cannot convert parameter 1 from 'const char *' to 'LPCWSTR' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

问题出在哪里?

推荐答案

std :: string由一个char型数组组成,因此 c_str 函数返回一个 const char * .

A std::string consists of an array of char's, and so the c_str function returns a const char*.

LPCWSTR 是指向常量宽字符串的长指针,换句话说,就是 const wchar_t * .

A LPCWSTR is a Long Pointer to a Constant Wide String, or in other words, const wchar_t*.

因此,您有两种选择.要么以宽字符串(std :: wstring)的形式获取文件名,要么指定您想要的是CreateFile的非宽版本.可以通过调用CreateFileA或在项目设置中禁用UNICODE来完成.

So you have a couple of options. Either get the filename as a wide string (std::wstring), or specify that you want the non-wide version of CreateFile instead. That can be done either by calling CreateFileA or disabling UNICODE in your project settings.

CreateFile是一个宏,它根据是否启用unicode解析为CreateFileA(字符版本)或CreateFileW(宽字符版本).

CreateFile is a macro which either resolves to CreateFileA (the char version) or CreateFileW (the wide char version) depending on whether or not unicode is enabled.

这篇关于Windows上的C ++ std :: string转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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