[英]argument of type “const char *” is incompatible with parameter of type “LPCWSTR”
[英]argument of type “char *” is incompatible with parameter of type "STRSAFE_LPCWSTR
我有以下幾點:
DYNAMIC_TIME_ZONE_INFORMATION dtzRecorder;
GetDynamicTimeZoneInformation(&dtzRecorder);
我通常會執行以下操作來復制新名稱:
StringCchCopy(dtzRecorder.TimeZoneKeyName, 128, L"GMT Standard Time");
但現在我需要執行以下操作:
char tzKey[51];
std::string timezone("someTimeZOneName");
strncpy_s(MyStruct.tzKey, timezone.c_str(), _TRUNCATE);
StringCchCopy(dtzRecorder.TimeZoneKeyName, 128, MyStruct.tzKey); <--Error
但是我得到了錯誤:
“ char *”類型的參數與“ STRSAFE_LPCWSTR”類型的參數不兼容
如何將其復制到dtzRecorder.TimeZoneKeyName?
基本問題是dtzRecorder.TimeZoneKeyName
是一個寬字符串( wchar_t[]
),而tzKey
是一個窄字符串( char[]
)。
解決此問題的最簡單方法是也將wchar_t
用於tzKey
:
wchar_t tzKey[51];
std::wstring timezone(L"someTimeZOneName");
wcsncpy_s(MyStruct.tzKey, timezone.c_str(), _TRUNCATE);
StringCchCopy(dtzRecorder.TimeZoneKeyName, 128, MyStruct.tzKey);
LPSTR
是Microsoft的“指向STRing的長指針”或char *
, LPWSTR
是Microsoft的“指向Wide-c STring的長指針”或wchar_t *
。 另外, LPCSTR
和LPCWSTR
引用const變體。
您看到的錯誤來自將LPCSTR
(常量字符指針)傳遞給需要LPWSTR
(非常量Unicode /寬字符指針)的函數。
寬字符串常量用L
前綴( L"wide"
)表示,通常具有wchar_t*
類型,並且需要std::string
的變體std::wstring
。
大多數Windows系統調用的默認設置由常規項目設置“字符集”處理,如果為“ Unicode”,則需要寬字符串。 <tchar.h>
提供對此的支持,請參見https://msdn.microsoft.com/zh-cn/library/dybsewaf.aspx
#include <tchar.h>
// tchar doesn't help with std::string/std::wstring, so use this helper.
#ifdef _UNICODE
#define TSTRING std::wstring
#else
#define TSTRING std::string
#endif
// or as Matt points out
typedef std::basic_string<_TCHAR> TSTRING;
// Usage
TCHAR tzKey[51]; // will be char or wchar_t accordingly
TSTRING timezone(_T("timezonename")); // string or wstring accordingly
_tscncpy_s(tzKey, timezone.c_str(), _TRUNCATE);
另外,您也可以明確使用范圍
wchar_t tzKey[51]; // note: this is not 51 bytes
std::wstring timezone(L"timezonename");
wscncpy_s(tzKey, timezone.c_str(), _TRUNCATE);
順便說一句,為什么不簡單地這樣做:
std::wstring timezone(L"tzname");
timezone.erase(50); // limit length
當您只可以在限制處插入空終止符時,為什么要浪費時間來復制值?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.