如何将REG_MULTI_SZ值写入注册表

How do I write REG_MULTI_SZ values to the Registry?

本文关键字:注册表 SZ MULTI REG      更新时间:2023-10-16

我正在尝试使用c++编写REG_MULTI_SZ值到Windows注册表。我卡住的地方是在转换我必须MULTI_SZ格式的c字符串。有什么方便的方法吗?

你得自己做。鉴于

char ** strings; // array of strings
int N; // number of strings

计算multi_sz

的长度
int len=1;
for(int i=0; i<N; i++)
  len += strlen(strings[i])+1;

并填充

char* multi_sz = malloc(len), ptr=multi_sz;
memset(multi_sz, 0, len);
for(int i=0; i<N; i++) {
  strcpy(ptr, strings[i]);
  ptr += strlen(strings[i])+1;
}

这是一个c++ 0x的替代方案。

static const std::string vals [] = 
{
    "a", "bb", "ccc"
};
static const size_t num_vals = sizeof(vals)/sizeof(vals[0]);
std::string reg_out = std::accumulate(&vals[0], &vals[num_vals], std::string(), [](std::string& so_far, const std::string& cur) -> std::string
{
    so_far += cur;
    so_far += '';
    return so_far;
});
reg_out += '';
reg_out.size();
RegSetValueEx(...,...,...,REG_MULTI_SZ, rerinterpret_cast<const BYTE*>(&reg_out[0]), reg_out.size());

如果所有值都是常量,那么您可能需要使用字符串字面值,而不是不必要地组合字符串。

如果你用字符串字面值构造一个c++字符串,那么第一个空字符将终止它:

string s("aaabbb");  // constructs the string "aaa"

但是,c++字符串可以包含空字符,并且可以从包含空字符的字符串字面量构造,如下所示:

const char sz[] = "aaabbb";
string szs(sz, sizeof(sz) / sizeof(char));  // constructs the string "aaabbb"

然后你可以简单地做:

RegSetValueEx(...,...,...,REG_MULTI_SZ, rerinterpret_cast<const BYTE*>(&szs[0]), szs.size());

请注意,与其他答案中建议的不同,不需要在值的末尾使用两个空字符(一个用于终止最后一个字符串,另一个用于终止列表)。这样做实际上会将一个空字符串添加到值列表中,这可能是不希望的。在本例中,第二个字符串(以及整个列表)以null字符结束,该字符被自动添加到c++字符串的末尾。