Can someone explain why this works:
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
Public Class MEMORYSTATUSEX
Public Sub New()
Me.dwLength = CType(Marshal.SizeOf(GetType(MEMORYSTATUSEX)), UInt32)
End Sub
Public dwLength As UInt32
Public dwMemoryLoad As UInt32
Public ullTotalPhys As UInt64
Public ullAvailPhys As UInt64
Public ullTotalPageFile As UInt64
Public ullAvailPageFile As UInt64
Public ullTotalVirtual As UInt64
Public ullAvailVirtual As UInt64
Public ullAvailExtendedVirtual As UInt64
End Class
And this doesn't:
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
Structure MEMORYSTATUSEX
Public Sub New(ByVal dwlength As UInt32)
Me.dwLength = dwlength
End Sub
Public dwLength As UInt32
Public dwMemoryLoad As UInt32
Public ullTotalPhys As UInt64
Public ullAvailPhys As UInt64
Public ullAvailPageFile As UInt64
Public ullTotalVirtual As UInt64
Public ullAvailVirtual As UInt64
Public ullAvailExtendedVirtual As UInt64
End Structure
When calling both structures/class from another class like this:
Dim newpoint As New Structures.MEMORYSTATUSEX()
GlobalMemoryStatusEx(newpoint)
And the 2nd:
Dim newpoint As New Structures.MEMORYSTATUSEX(CType(Marshal.SizeOf(GetType(Structures.MEMORYSTATUSEX)), UInt32))
GlobalMemoryStatusEx(newpoint)
They're both inside a class, when i call the second with the size parameter it throws "A first chance of AccessViolationException" on the GlobalMemoryStatusEx(newpoint)
call and crashes the application.
I can't understand why since the dwLength value is initialized on both in the constructor? Am i right?
The reason i want to change the first example is because i'm moving all Structures to a Structure-Only class, and thought this would be a good idea until i coudln't understand why this didn't work, since the same value is set before the call to the API occurs.
P/Invoke declarations:
<DllImport("kernel32.dll", SetLastError:=True)> _
Private Shared Function GlobalMemoryStatusEx(lpBuffer As Structures.MEMORYSTATUSEX) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Error's Detail:
A first chance exception of type 'System.AccessViolationException' occurred in Client.exe
Additional information: Attempt of read or write protected memory...
If i click continue:
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
Additional information: exception has been thrown by the target of an invocation