“char *”类型的参数与“STRSAFE_LPCWSTR”类型的参数不兼容

时间:2015-05-27 22:44:31

标签: c++ string strsafe

我有以下内容:

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 ??

2 个答案:

答案 0 :(得分:2)

基本问题是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); 

答案 1 :(得分:1)

LPSTR是微软用于“指向长串指针”或char *LPWSTR是微软用于“指向广角网站的长指针”或wchar_t *。另外LPCSTRLPCWSTR引用const变体。

您看到的错误来自于将LPCSTR(const字符指针)传递给期望LPWSTR(非const unicode / wide字符指针)的函数。

宽字符串常量用L前缀(L"wide")表示,通常具有wchar_t*类型,并且需要std::string的变体std::wstring

大多数Windows系统调用的默认值由一般项目设置“字符集”处理,如果是“Unicode”则需要宽字符串。 <tchar.h>https://msdn.microsoft.com/en-us/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

为什么浪费时间复制值只能在限制时插入空终止符?