I this short post I will not dive into details describing why PInvoke is essential to writing Windows based applications. Most people who are referred to this page by search engine already know what it is and have an issue of System.AccessViolationException
popping when invoking one of Win32 API functions. In my case, reason for this exception appeared to be trivial – usage of wrong parameter type in the function signature. Namely, I was trying to set power scheme:
[DllImport(“powrprof.dll”, SetLastError = true)]
public static extern UInt32 PowerSetActiveScheme(IntPtr UserRootPowerKey, Guid SchemeGuid);
And the error I kept on getting was:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Test.Win32Imports.PowerSetActiveScheme(IntPtr UserRootPowerKey, Guid SchemeGuid)
Eventually, it appeared that I had error function signature definition (should have passed second parameter as reference), and the correct definition is:
[DllImport(“powrprof.dll”, SetLastError = true)]
public static extern UInt32 PowerSetActiveScheme(IntPtr UserRootPowerKey, ref Guid SchemeGuid);
Stupid mistake that took me far too long to notice. Hope that it gave you lead how to solve your System.AccessViolationException
.