Saher Ahwal
Saher Ahwal

Reputation: 9237

Cannot Derefrence IntPtr in C#

I wrote a class that implements the IGroupPolicyObject Interface in COM. one of the method now returns IntPtr object in C#:

IntPtr ghKey = objectGPolicy.GetRegistryKey(GpoSectionMachine);

I want to derefrence that pointer when using the RegistryKey object that belongs to Microsot.Win32 namespace.

This DOESN'T work:

(RegistryKey)ghKey = rootKey.CreateSubKey(policyPath);

I can't find how to derefrence an IntPtr. Can someone help please?

Thanks

Upvotes: 0

Views: 553

Answers (1)

Michael Edenfield
Michael Edenfield

Reputation: 28338

IGroupPolicyObject.GetRegistryKey doesn't return a .NET RegistryKey object, it returns a Win32 registry key handle (an HKEY). There are two useful things you can do with an IntPtr value that contains a native HKEY. First, you can pass it to other Win32 registry access functions. If you use it this way, you also need to manually close it by calling RegCloseKey when you're done, or it will leak the handle.

As @HansPassant helpfully points out in his comment, your second (and probably better) option is to turn it into a SafeRegistryHandle and use it to get a RegistryKey object:

var hkey = gpo.GetRegistryKey(GpoSectionMachine);
var safeHandle = new SafeRegistryHandle(hkey, true);
var reg = RegistryKey.FromHandle(safeHandle);

If you wrote a managed implementation of IGroupPolicyObject and it returns an actual RegistryKey object from this function, then:

  1. You did it wrong and your implementation is not portable to any other consumer of IGroupPolicyObject, and
  2. You must have manually marshalled your RegistryKey object into an IntPtr in your implementation, so just do the opposite to get it back out. (But really -- don't do that, you are breaking the COM contract by returning the wrong type.)

An implementation of this method should instead be written to return a SafeRegistryHandle (the marshaler will, I believe, automatically convert between SafeHandle and an unmanaged handle). RegistryKey.Handle is one of these so you can use the C# classes right up until you need to return something from your implementation.

Upvotes: 6

Related Questions