2

I'm trying to get the value of registry key and then to see it

following extract of code

HKEY hkey;

RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\SomeSoft\\Settings", 0, 0x20019u, &hKey);

printf("121 hkey= %s \n", hKey);    

is compiling, but stopped at runtime.

Question: how do I convert hkey in something visible, like string in order to see it?

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
user3095293
  • 31
  • 1
  • 2
  • "casting" is not really a good tag for this question. I am going to also assume C++ as you did not specify a language. – Moo-Juice Dec 16 '13 at 12:07
  • If you want to get the string representation for a given `HKEY` value (i.e. you want your program to print something like `HKEY_CURRENT_USER\Software\SomeSoft\Settings`) see [this question](http://stackoverflow.com/questions/937044/determine-path-to-registry-key-from-hkey-handle-in-c) – Frerich Raabe Dec 16 '13 at 12:13

3 Answers3

1

An HKEY is not a string, rather it is an integer value. So, what happens is that your program treats hKey as if it were a null-terminated array of char and presumably that's what leads to the runtime failure.

You must use an appropriate format string for the type of data that you have. This is one of the pitfalls of printf and is one of the reasons why, if you can, you should prefer the C++ stream output mechanism.

Note that HKEY is pointer sized. So if you want your code to work for both 32 and 64 bit processes then you will need to allow for that in your format string. The easiest thing is to treat it as a pointer and use %p.

You should also make sure that you perform error checking. You are ignoring the return value of RegOpenKeyEx, and you must not do that. I would not be at all surprised if the real problem with your code was revealed simply by paying heed to the value returned by the function.

And don't use magic constants for the samDesired parameter. Specify it by combining flags using the bitwise or operator. Or in your case, pass KEY_READ.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

I'm not quite sure what you mean by "converting a HKEY to a string":

  1. If you want to get the numeric value of the HKEY, print it like you would print a pointer, e.g.

    printf( "hkey = %p\n", hkey );
    
  2. If you want to print the path represented by the HKEY handle, see this answer.

  3. If you want to print the string value of the registry entry referenced by a HKEY, use the RegQueryValueEx function.

Community
  • 1
  • 1
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
1

The returned HKEY is a handle. Use RegQueryValueEx to get the actual registry value.

mark
  • 5,269
  • 2
  • 21
  • 34