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。您可以使用转换字符串