如何在registry.GetValue中使用[]byte作为缓冲区?

How to use []byte as a buffer in registry.GetValue?

GetValue() 的注册表包中的文档说:

GetValue retrieves the type and data for the specified value associated with an open key k. It fills up buffer buf and returns the retrieved byte count n. If buf is too small to fit the stored value it returns ErrShortBuffer error along with the required buffer size n. If no buffer is provided, it returns true and actual buffer size n. If no buffer is provided, GetValue returns the value's type only. If the value does not exist, the error returned is ErrNotExist.

GetValue 是一个低级函数。 如果值的类型已知,请改用适当的 Get*Value 函数。

就我而言,我不知道注册表项的值类型。但是,我只需要将值打印为字符串。 GetValue() 接受值名称和 "buffer" 但缓冲区的类型为 []byte。它不是通过引用传递的,所以我不能只创建 var buf []byte,将其传入并读取。我不能用 &buf (type *[]byte) 传递它。我不能使用 byte.Buffer (也键入不匹配)。我觉得我缺少了一些非常简单的东西。

代码:

var buf []byte //????
_, _, e := myKey.GetValue(valuename, buf)
if e != nil {
    panic(e)
}
fmt.Printf("Value: %s\n", string(buf)) // Prints blank

我想您提到的注册表 API 是 Windows 注册表。要使用这些类型的 APIs,您必须对调用的输出大小进行最佳猜测:

buf:=make([]byte,1024)
typ, n, e := myKey.GetValue(valuename, buf)
if e==ErrShortBuffer {
   // Go back, try with a larger buffer size
   buf=make([]byte,n)
   typ, n, e = myKey.GetValue(valuename, buf)
}