簡體   English   中英

如何將REG_MULTI_SZ值寫入注冊表?

[英]How do I write REG_MULTI_SZ values to the Registry?

我正在嘗試使用C ++將REG_MULTI_SZ值寫入Windows注冊表。 我遇到的困難是將必須轉換的C字符串轉換為MULTI_SZ格式。 有方便的方法嗎?

這是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 += '\0';
    return so_far;
});
reg_out += '\0';
reg_out.size();

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

您必須自己做。 特定

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 ++字符串,則第一個空字符將終止它:

string s("aaa\0bbb");  // constructs the string "aaa"

但是,C ++字符串可以包含空字符,並且可以由包含空字符的字符串文字構造,如下所示:

const char sz[] = "aaa\0bbb";
string szs(sz, sizeof(sz) / sizeof(char));  // constructs the string "aaa\0bbb"

然后,您可以簡單地執行以下操作:

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

需要注意的是,不像是什么在其他的答案建議, 沒有必要在值的末尾兩個空字符(一個用於終止最后一個字符串和一個用於終止列表)。 這樣做實際上會將一個空字符串添加到值列表中,這可能是不希望的。 在此示例中,第二個字符串(和整個列表)以空字符終止,該空字符會自動添加到C ++字符串的末尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM