[2005] Win32 API Error: "Attempted to read or write protected memory."
Hey Guys,
Trying to play with the Win32 API but am getting the following error:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt." {System.AccessViolationException}
This occurs during a call to CreateFile():
VB Code:
sFullDrivePath = "\\.\" & sDriveLetter & ":"
hDevice = CreateFile(sFullDrivePath, GENERIC_READ, FILE_SHARE_READ Or FILE_SHARE_WRITE, vbNull, OPEN_EXISTING, 0, 0)
I am attempting to open a USB disk but when I call CreateFile() to get my handle it fails...
I am on a machine that is part of a domain, I am a local admin but not domain admin. Therefore I should have enough rights to perform this operation? You only need full admin to open a hard disk.
Any ideas?
Thanks,
Matt.
Re: [2005] Win32 API Error: "Attempted to read or write protected memory."
I assume this has to be a security issue with the framework.
I am making an unmanaged call but the error I am receiving is caught by the managed code.
How can I tell the framework to back off its security?
Matt.
Re: [2005] Win32 API Error: "Attempted to read or write protected memory."
It is quite likely to be an error in your API declaration.
Can you post that?
Also - vbNull is not a .NET friendly thing at all.
Re: [2005] Win32 API Error: "Attempted to read or write protected memory."
Hey Merrion,
You got it! But didn't....
I simply changed the vbNull to 0 and BOOM, my device handle is returned!
So I was very happy for a second until I then tried to move the file pointer using SetFilePointer() and got the same error!
VB Code:
<DllImport("kernel32.dll")> _
Public Function SetFilePointer( _
ByVal hFile As Long, _
ByVal lDistanceToMove As Long, _
ByVal lpDistanceToMoveHigh As Long, _
ByVal dwMoveMethod As Long) As Long
End Function
Public Const FILE_BEGIN As Long = 0
Public Const FILE_EOF As Long = &HFFFFFFFF
Used like so:
VB Code:
If SetFilePointer(hDevice, (iSectorSize * iSectorNumber), 0, FILE_BEGIN) = FILE_EOF Then
MessageBox.Show("Unable to find sector " & iSectorNumber, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return baDataBuffer
End If
This threw the same "Attempted to read or write....." error. Hmmmmmm
Thanks Merrion,
Matt.
Re: [2005] Win32 API Error: "Attempted to read or write protected memory."
OK - with the api declaration we can see a problem.
In .NET an integer is 32 bits so replace Long with Integer:-
VB Code:
<DllImport("kernel32.dll")> _
Public Function SetFilePointer( _
ByVal hFile As Int32 , _
ByVal lDistanceToMove As int32, _
ByVal lpDistanceToMoveHigh As Int32, _
ByVal dwMoveMethod As Int32) As Int32
End Function
Public Const FILE_BEGIN As Int32 = 0
Public Const FILE_EOF As int32 = &HFFFFFFFF