//简单的DDK实例--C语言
#include <ntddk.h>
//请记住:在Ring0环,内存资源很宝贵
#define INITCODE code_seg("INIT") //初始化内存
#define PAGECODE code_seg("PAGE") //分页内存(内存资源紧张时,可以置换到硬盘)
#define NPAGECODE code_seg() //非分页内存(常驻内存中)
#pragma INITCODE
NTSTATUS CreateMyDevice(IN PDRIVER_OBJECT pDriverObject); //创建设备对象
#pragma PAGECODE
NTSTATUS DispathFunction(IN PDEVICE_OBJECT pDeviceObject, IN PIRP Irp); //默认分发处理例程
#pragma INITCODE
VOID DDK_Unload(IN PDRIVER_OBJECT pDriverObject); //卸载例程
#pragma INITCODE
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING B) //驱动入口函数
{
int i;
KdPrint(("驱动成功被加载...OK++++++++"));
//设置卸载例程
pDriverObject->DriverUnload = DDK_Unload;
//设置默认分发处理例程
for(i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++)
{
pDriverObject->MajorFunction[i] = DispathFunction;
}
//创建设备对象
CreateMyDevice(pDriverObject);
return STATUS_SUCCESS;
}
//默认分发处理例程
NTSTATUS DispathFunction(IN PDEVICE_OBJECT pDeviceObject, IN PIRP Irp)
{
//完成IRP
Irp->IoStatus.Status = STATUS_SUCCESS; //设置IRP的状态为成功
Irp->IoStatus.Information = 0; //设置操作的字节数为0
IoCompleteRequest(Irp, IO_NO_INCREMENT); //指示完成此IRP请求
return Irp->IoStatus.Status;
}
//创建设备对象例程函数
NTSTATUS CreateMyDevice(IN PDRIVER_OBJECT pDriverObject)
{
NTSTATUS status;
//用来返回创建设备对象
PDEVICE_OBJECT pDevObj;
//设备名称
UNICODE_STRING devName;
//连接符
UNICODE_STRING symLinkName;
//对devName初始化字串为 "\Device\xx_Device"
RtlInitUnicodeString(&devName, L"\Device\xx_Device");
//创建设备对象
status = IoCreateDevice(pDriverObject,
0,
&devName,
FILE_DEVICE_UNKNOWN,
0, TRUE,
&pDevObj);
if (!NT_SUCCESS(status))
{
if (status == STATUS_INSUFFICIENT_RESOURCES)
{
KdPrint(("资源不足 STATUS_INSUFFICIENT_RESOURCES"));
}
if (status == STATUS_OBJECT_NAME_EXISTS)
{
KdPrint(("指定对象名存在"));
}
if (status == STATUS_OBJECT_NAME_COLLISION)
{
KdPrint(("//对象名有冲突"));
}
KdPrint(("设备创建失败...++++++++"));
return status;
}
//设置缓冲区通信方式
pDevObj->Flags |= DO_BUFFERED_IO;
//创建符号链接
RtlInitUnicodeString(&symLinkName,L"\??\XX_Device");
status = IoCreateSymbolicLink( &symLinkName,&devName );
if (!NT_SUCCESS(status))
{
//删除设备对象
IoDeleteDevice( pDevObj );
return status;
}
return STATUS_SUCCESS;
}
//卸载例程函数
VOID DDK_Unload(IN PDRIVER_OBJECT pDriverObject)
{
KdPrint(("驱动成功被卸载...OK-----------"));
}
//参考资料:
//郁金香老师讲课资料整理