Access Violation Invoking C # Win API Using DllImport

The task is to determine the last time entries for the registry key. Since the standard RegistryKey class does not provide this function, I have to use the WinAPI function "RegQueryInfoKey". To get the key descriptor, I open it with "RegOpenKeyEx".

This is a WinAPI function prototype (taken from MSDN):

LONG WINAPI RegOpenKeyEx( __in HKEY hKey, __in LPCTSTR lpSubKey, DWORD ulOptions, __in REGSAM samDesired, __out PHKEY phkResult ); 

I use the following expression:

 [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int RegOpenKeyEx(UIntPtr hkey, string lpSubKey, uint samDesired, ref UIntPtr phkResult); 

Then I call it like this:

 UIntPtr hKey = UIntPtr.Zero; string myKeyName = "blablabla"; UIntPtr HKEY_USERS = (UIntPtr)0x80000003; uint KEY_READ = 0x20019; RegOpenKeyEx(HKEY_USERS, myKeyName, KEY_READ, ref hKey); 

At this point, I get an "Access Violation" exception. What am I doing wrong? I think something is wrong with passing parameters, but how to do it right?

Thanks.

+4
source share
2 answers

There are 5 parameters in the prototype of a native function, and only 4 in your P / Invoke signature.

In particular, you are missing DWORD ulOptions . This parameter is "reserved and must be zero" according to the MSDN documentation, but it should still be passed in a function call.

In addition, you do not need to set the SetLastError field, because the RegOpenKeyEx function returns its error code; you do not need to retrieve it by raising GetLastError . Therefore, you do not need a marshaler to automatically save this value for you. Just check the return value for the error code.

Change your P / Invoke signature to:

 [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int RegOpenKeyEx(UIntPtr hkey, string lpSubKey, uint ulOptions, uint samDesired, out UIntPtr phkResult); 

An incorrect P / Invoke signature is almost always the cause of "access violation" errors. When you see one of them, make sure to double-check it twice.

+4
source

You missed ulOptions from your P / Invoke signature.

+4
source

Source: https://habr.com/ru/post/1387852/


All Articles