mydriver2.c:
#include "ntddk.h" VOID CleanUp(IN PDRIVER_OBJECT pDriverObject) { DbgPrint("my second driver's cleanUp routine called"); } NTSTATUS OpenFunction(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("Open Function called"); return STATUS_SUCCESS; } NTSTATUS CloseFunction(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("Close Function called"); return STATUS_SUCCESS; } NTSTATUS ReadFunction(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("Read Function called"); return STATUS_SUCCESS; } NTSTATUS WriteFunction(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("Write Function called"); return STATUS_SUCCESS; } NTSTATUS IoControlFunction(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("IoControlFunction Function called"); return STATUS_SUCCESS; } const WCHAR deviceNamePath[] = L"\\Device\\DeviceName"; // Define the device const WCHAR dosDeviceNamePath[] = L"\\DosDevices\\DosDeviceName"; // Define the device PDEVICE_OBJECT pDeviceObject; // Pointer to device object NTSTATUS DriverEntry(IN PDRIVER_OBJECT TheDriverObject, IN PUNICODE_STRING TheRegistryPath) { NTSTATUS ntStatus = 0; UNICODE_STRING deviceLinkUnicodeString; UNICODE_STRING deviceName; UNICODE_STRING dosDeviceName; DbgPrint("This is my second driver!"); TheDriverObject->DriverUnload = CleanUp; // We set up the name and symbolic link in Unicode RtlInitUnicodeString(&deviceName, deviceNamePath); RtlInitUnicodeString(&dosDeviceName, dosDeviceNamePath); // Set up the device myDevice ntStatus = IoCreateDevice(TheDriverObject, 0,// Driver extension &deviceName, FILE_DEVICE_FILE_SYSTEM, 0, TRUE, &pDeviceObject); if (NT_SUCCESS(ntStatus)) { ntStatus = IoCreateSymbolicLink(&dosDeviceName, &deviceName); } TheDriverObject->MajorFunction[IRP_MJ_CREATE] = OpenFunction; TheDriverObject->MajorFunction[IRP_MJ_CLOSE] = CloseFunction; TheDriverObject->MajorFunction[IRP_MJ_READ] = ReadFunction; TheDriverObject->MajorFunction[IRP_MJ_WRITE] = WriteFunction; TheDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = IoControlFunction; return STATUS_SUCCESS; }
TARGETNAME=MYDRIVER2 TARGETPATH=OBJ TARGETTYPE=DRIVER SOURCES=mydriver2.c
再用VS2010编写测试程序UserLand.cpp:
#include <stdio.h> #include <Windows.h> int main() { HANDLE hDevice; TCHAR *lpszDeviceName = L"\\\\.\\DosDeviceName"; TCHAR szWrite[100] = L"write something", szRead[100]; DWORD dwWrite, dwRead; hDevice = CreateFile(lpszDeviceName,GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); wprintf(L"Handle pointer: %p\n",hDevice); WriteFile(hDevice, szWrite, sizeof(szWrite), &dwWrite, NULL); wprintf(L"write:%s\n",szWrite); CloseHandle(hDevice); hDevice = CreateFile(lpszDeviceName,GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); ReadFile(hDevice, szRead, sizeof(szRead), &dwRead, NULL); wprintf(L"read:%s\n",szRead); CloseHandle(hDevice); return 0; }