//最简单的NT式驱动程序
//A Simple kernel-mode driver.
 
extern "C"
{
    #include <ntddk.h>
};
 
//设备扩展:其实是自己定义的附加信息
struct DEVICE_EXTENSION
{
    PDEVICE_OBJECT pDevObj;
    UNICODE_STRING ustr_SymbolicLinkName;
};
 
VOID SimpleDriver_Unload(IN PDRIVER_OBJECT pDriverObject)
{
    //遍历设备链,删除设备,删除符号链接
    //设备链是个普通链表
    PDEVICE_OBJECT pDevObj=pDriverObject->DeviceObject;
    while(pDevObj!=NULL)
    {
        DEVICE_EXTENSION* pDevExt=(DEVICE_EXTENSION*)(pDevObj->DeviceExtension);
        IoDeleteSymbolicLink(&(pDevExt->ustr_SymbolicLinkName));
        IoDeleteDevice(pDevExt->pDevObj);
 
        pDevObj=pDevObj->NextDevice;
    }
 
    KdPrint(("2.SimpleDriver_Unload()\n"));
}
 
 
extern "C" NTSTATUS DriverEntry(
                     IN PDRIVER_OBJECT  pDriverObject,
                     IN PUNICODE_STRING pRegistryPath)
{
   
    //指定卸载(此处的卸载是指此驱动程序停止运行时)例程
    KdPrint(("1.SimpleDriver DriverEntry()\n"));
    pDriverObject->DriverUnload=SimpleDriver_Unload;
 
    //初始化设备名称
    //格式为:\Device\DeviceName
    UNICODE_STRING ustr_DevName;
    RtlInitUnicodeString(&ustr_DevName,L"\\Device\\SimpleDriver_Device0");
                             
    //主动创建设备
    PDEVICE_OBJECT pDevObj;
    NTSTATUS status=IoCreateDevice(
        pDriverObject,
        sizeof(DEVICE_EXTENSION),
        &ustr_DevName,
        FILE_DEVICE_UNKNOWN,
        0,
        TRUE,
        &pDevObj);
          
    if (NT_SUCCESS(status)){
        KdPrint(("1.1.IoCreateDevice() OK\n"));
    }
    else{
        KdPrint(("1.1.IoCreateDevice() Failed\n"));
        return status;
    }
 
    //设置设备扩展信息(根据需要,保存各种附加信息)
    //DEVICE_EXTENSION是自己定义的结构体
    DEVICE_EXTENSION* pDevExt=(DEVICE_EXTENSION*)(pDevObj->DeviceExtension);
    pDevExt->pDevObj=pDevObj;
 
    //初始化链接名称字符串
    //格式为:\??\SymbolicLinkName
    UNICODE_STRING ustr_SymbolicLinkName;
    RtlInitUnicodeString(&ustr_SymbolicLinkName,L"\\??\\SimpleDriver_Device0");
   
    //创建符号链接
    status=IoCreateSymbolicLink(&ustr_SymbolicLinkName,&ustr_DevName);
    if (NT_SUCCESS(status)){
        KdPrint(("1.2.IoCreateSymbolicLink() OK\n"));
        pDevExt->ustr_SymbolicLinkName=ustr_SymbolicLinkName;
    }
    else{
        KdPrint(("1.2.IoCreateSymbolicLink() Failed\n"));
        return status;
    }
 
    return STATUS_SUCCESS;
}
 
用DriverMonitor加载后,在DeviceTree中可以看到:
 

本文链接地址: 驱动编程.4 最简单的NT式驱动程序
http://qingfengju.com/index.asp?id=188

分类:Win32/C++ 查看次数:6180 发布时间:2009-12-22 14:47:51