A Confused Programmer's Blog

This blog is dedicated to C# and Java programming that I happen to do for living – with accent on curious cases and with sincere intent to make the world of coding a slightly better place as a result

Possible reason of System.AccessViolationException when using PInvoke

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.

Comments are closed.

Subscribe to email feed

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube

REST Assured and une

If you stumbled onto this article, it is safe to ...

Getting rid of Error

Since I upgraded my Windows 8 to Windows 10, I ...

Bypassing EULA step

We are working on automated testing of virtual appliance. This appliance ...

How I got rid of "Ac

OVF is a VMware virtual appliance format which allows you ...

My use-case of Perfo

In my blog I am set on a mission to ...

Twitter updates

RSS not configured