C++ 类型为“的参数”;字符*”;与类型为“的参数不兼容”;STRSAFE_LPCWSTR
我有以下资料:C++ 类型为“的参数”;字符*”;与类型为“的参数不兼容”;STRSAFE_LPCWSTR,c++,string,strsafe,C++,String,Strsafe,我有以下资料: DYNAMIC_TIME_ZONE_INFORMATION dtzRecorder; GetDynamicTimeZoneInformation(&dtzRecorder); char tzKey[51]; std::string timezone("someTimeZOneName"); strncpy_s(MyStruct.tzKey, timezone.c_str(), _TRUNCATE); StringCchCopy(dtzRecorder.TimeZon
DYNAMIC_TIME_ZONE_INFORMATION dtzRecorder;
GetDynamicTimeZoneInformation(&dtzRecorder);
char tzKey[51];
std::string timezone("someTimeZOneName");
strncpy_s(MyStruct.tzKey, timezone.c_str(), _TRUNCATE);
StringCchCopy(dtzRecorder.TimeZoneKeyName, 128, MyStruct.tzKey); <--Error
我通常会执行以下操作来复制新名称:
StringCchCopy(dtzRecorder.TimeZoneKeyName, 128, L"GMT Standard Time");
但现在我需要做以下工作:
DYNAMIC_TIME_ZONE_INFORMATION dtzRecorder;
GetDynamicTimeZoneInformation(&dtzRecorder);
char tzKey[51];
std::string timezone("someTimeZOneName");
strncpy_s(MyStruct.tzKey, timezone.c_str(), _TRUNCATE);
StringCchCopy(dtzRecorder.TimeZoneKeyName, 128, MyStruct.tzKey); <--Error
chartzkey[51];
std::字符串时区(“someTimeZOneName”);
strncpy_s(MyStruct.tzKey,timezone.c_str(),_TRUNCATE);
StringCchCopy(dtzRecorder.TimeZoneKeyName,128,MyStruct.tzKey) 基本问题是dtzRecorder.TimeZoneKeyName
是一个宽的字符串(wchar\u t[]
),但tzKey
是一个窄的字符串(char[]
)
解决此问题的最简单方法是将wchar\u 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的“长指针指向字符串”或char*
,LPWSTR
是Microsoft的“长指针指向宽c字符串”或wchar\u t*
。另外,LPCSTR
和LPCWSTR
指的是const变体
您看到的错误来自将LPCSTR
(常量字符指针)传递给需要LPWSTR
(非常量unicode/宽字符指针)的函数
宽字符串常量用L
前缀(L“Wide”
)表示,通常具有wchar\u t*
类型,并且需要一个名为std::wstring
的std::string
变量
这是大多数Windows系统调用的默认值,由常规项目设置“字符集”处理,如果是“Unicode”,则需要宽字符串。对此的支持由
提供,请参见
另一方面,为什么不干脆这样做:
std::wstring timezone(L"tzname");
timezone.erase(50); // limit length
如果可以在限制处插入空终止符,为什么还要浪费时间复制值?尝试更改std::string timezone(“someTimeZOneName”)代码>到std::wstring时区(“someTimeZOneName”)
您可以使用typedef std::basic_string TSTRING
而不是使用#ifdef
。这些typedef中的C
表示const
LPSTR
是char*
,LPCSTR
是const char*
,OP拥有的LPCWSTR
是const wchar\u t*
。抱歉,我忘了提及我不能更改tzKey字符串,因为它在其他地方使用。我只需要以某种方式将MyStruct.tzKey转换为dtzRecorder.TimeZoneKeyName。您可以使用转换字符串