Question API WriteFile Protected Memory Access Issue

sebeka

New member
Joined
May 22, 2009
Messages
4
Programming Experience
5-10
Hi,

I'm currently using an unmanaged library written in C++ and imported via <DLLImport()> to access a dos virtual device driver, and that works fine. However, I'd like to be able to do this via my .NET application (without requiring an accompanying DLL). So, I'm trying to write to the virtual dos device using the kernel32 API and WriteFile, however I receive the error: "Attempted to read or write protected memory."

Mapping to the device with DefineDosDevice and CreateFile (also in the kernel32 API) works fine and returns a valid file handle, however when I attempt to write to the file it fails. I've even tried marshaling the data to an unmanaged block of memory using InteropServices (AllocHGlobal and StructureToPtr) and then writing it from there, however I still receive the same error.

Might anyone have some advice? Thanks in advance!
-S
 
As it turns out I just had the wrong API declarations. So, all is working now. If anyone is interested, below are the declarations to interface with a device driver directly from VB.NET. And, you do need to marshal your packet into an unmanaged area of memory before using DeviceIOControl and WriteFile.

VB.NET:
    Public Declare Function DefineDosDevice Lib "kernel32" Alias _
    "DefineDosDeviceA" (ByVal dwFlags As UInteger, _
    ByVal lpDeviceName As String, _
    Optional ByVal lpTargetPath As String = vbNullString) As Long

    Public Declare Function CreateFile Lib "kernel32" _
    Alias "CreateFileA" (ByVal lpFileName As String, _
    ByVal dwDesiredAccess As Int32, ByVal dwShareMode As Int32, _
    ByVal lpSecurityAttributes As IntPtr, _
    ByVal dwCreationDisposition As Int32, _
    ByVal dwFlagsAndAttributes As Int32, ByVal hTemplateFile As IntPtr) As IntPtr

    Public Declare Function WriteFile Lib "kernel32" ( _
    ByVal hFile As IntPtr, ByVal lpBuffer As IntPtr, _
    ByVal nNumberOfBytesToWrite As Long, _
    ByRef lpNumberOfBytesWritten As Long, ByVal lpOverlapped As Long) As Long

    Public Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

    <System.Runtime.InteropServices.DllImport("kernel32.dll", ExactSpelling:=True, SetLastError:=True, CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
    Public Function DeviceIoControl(ByVal hDevice As IntPtr, _
     ByVal dwIoControlCode As Int32, ByVal lpInBuffer As IntPtr, _
     ByVal nInBufferSize As Int32, ByVal lpOutBuffer As IntPtr, _
     ByVal nOutBufferSize As Int32, ByRef lpBytesReturned As Int32, _
     ByVal lpOverlapped As System.Threading.NativeOverlapped) As Boolean
    End Function
 
Back
Top