C++ “char *”类型的参数与“LPWSTR”类型的参数不兼容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20611865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:14:59  来源:igfitidea点击:

Argument of type "char *" is incompatible with parameter of type "LPWSTR"

c++

提问by OliverMller

This has probably been asked before but I can't seem to find the solution:

之前可能已经问过这个问题,但我似乎找不到解决方案:

std::string GetPath()
{
    char buffer[MAX_PATH];
    ::GetSystemDirectory(buffer,MAX_PATH);
    strcat(buffer,"\version.dll");

    return std::string(buffer);
}

This returns an error stating:

这将返回一个错误说明:

argument of type "char *" is incompatible with parameter of type "LPWSTR"

So yeah. Anyone got an answer?

是的。有人有答案吗?

回答by paulm

You need to use the ansi version:

您需要使用 ansi 版本:

std::string GetPath()
{
     char buffer[MAX_PATH] = {};
     ::GetSystemDirectoryA(buffer,_countof(buffer)); // notice the A
     strcat(buffer,"\version.dll");

     return std::string(buffer);
 }

Or use unicode:

或者使用 unicode:

std::wstring GetPath()
{
     wchar_t buffer[MAX_PATH] = {};
     ::GetSystemDirectoryW(buffer,_countof(buffer)); // notice the W, or drop the W to get it "by default"
     wcscat(buffer,L"\version.dll");

     return std::wstring(buffer);
 }

Rather than call the A/W versions explicitly you can drop the A/W and configure the whole project to use ansi/unicode instead. All this will do is change some #defines to replace foo with fooA/W.

您可以删除 A/W 并将整个项目配置为使用 ansi/unicode,而不是显式调用 A/W 版本。所有这些都会改变一些#defines 以用 fooA/W 替换 foo。

Notice that you should use _countof() to avoid incorrect sizes depending on the buffers type too.

请注意,您也应该使用 _countof() 来避免根据缓冲区类型的错误大小。

回答by kunal

If you compile your code using MultiByte support it will compile correctly,but when you compile it using Unicode flag it will give an error because in Unicode support ::GetSystemDirectoryA becomes ::GetSystemDirectoryW use consider using TCHAR instead of char.TCHAR is defined such that it becomes char in Multibyte flag and wchar_t with Unicode flag

如果您使用 MultiByte 支持编译代码,它将正确编译,但是当您使用 Unicode 标志编译它时,它将给出错误,因为在 Unicode 支持中 ::GetSystemDirectoryA 变为 ::GetSystemDirectoryW 使用考虑使用 TCHAR 而不是 char。TCHAR 被定义为它在多字节标志和 wchar_t 与 Unicode 标志中变为 char

TCHAR buffer[MAX_PATH];
::GetSystemDirectory(buffer,MAX_PATH);
_tcscat(buffer,_T("\version.dll"));

You can use typedef for string /wstring so your code becomes independent

您可以将 typedef 用于字符串 /wstring 以便您的代码变得独立

#ifdef UNICODE 
typedef wstring STRING;
#else
typedef string STRING;
#endif

STRING GetPath()
{
    TCHAR buffer[MAX_PATH];
    ::GetSystemDirectory(buffer,MAX_PATH);
    _tcscat(buffer,_T("\version.dll"));

    return STRING(buffer);
}