[英]C++ char conversion
I googled it for 2 hours now, and i can't find an answer for my problem: i need to get a registry REG_SZ
value and pass it to a char*
. 我现在用Google搜索了2个小时,但找不到我的问题的答案:我需要获取注册表REG_SZ
值并将其传递给char*
。
char host_val[1024];
DWORD hostVal_size = 1024;
char* hostName;
DWORD dwType = REG_SZ;
RegOpenKeyEx(//no problem here);
if( RegQueryValueEx( hKey, TEXT("HostName"), 0, &dwType, (LPBYTE)&host_val, &hostVal_size ) == ERROR_SUCCESS )
{
//hostName = host_val;
}
How should i do this conversion hostName = host_val
? 我该如何转换hostName = host_val
?
The resulting host_val
is a possibly non-null-terminated string (see "Remarks"), so you should copy it to a newly allocated string with memcpy
, and ensure it's null-terminated: 结果host_val
是一个可能为非空终止的字符串 (请参见“备注”),因此您应使用memcpy
将其复制到新分配的字符串中,并确保其为空终止:
hostName = new char[hostVal_size + 1];
// host_val may or may not be null-terminated
memcpy(hostName, host_val, hostVal_size);
hostName[hostVal_size] = '\0';
You will need to delete[]
the hostName
later. 您稍后需要delete[]
hostName
。
use the ANSI version of the function 使用函数的ANSI版本
RegQueryValueExA
that way you don't need to convert. 这样,您就无需转换。
If you're compiling with Unicode you're copying a Unicode string (that is possibly NOT terminated) into a narrow char buffer. 如果使用Unicode进行编译,则会将Unicode字符串(可能未终止)复制到狭窄的char缓冲区中。 the first character in the unicode string will be 0x3100 (accounting for the endianness on your machine, which is likely little-endian, and the fact that you said the IP address is 192....) unicode字符串中的第一个字符将是0x3100(说明您计算机上的字节序,这可能是小字节序,并且您说的IP地址是192 ....)
That value stuffed into the char[] array will report back as a single-char-null-terminated string. 填充到char []数组中的值将以单char-null终止的字符串形式返回。 You have two options. 您有两个选择。
For obvious reasons, I'd take the former of those two options. 出于明显的原因,我会选择这两个选项中的前一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.