类型为"char *"的参数与类型为"STRSAFE_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的"Long Pointer to STRing"或char *
, LPWSTR
是Microsoft的"Long Pointer to Wide-c STRing"或wchar_t *
。另外,LPCSTR
和LPCWSTR
引用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
当你可以在极限处插入空终止符时,为什么要浪费时间复制值呢?
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 类中的字符串不命名类型