1. 如何调用驱动功能
1 编写调用驱动的应用程序
1.1 定义驱动设备接口,以及调用接口的控制码
例如:
DEFINE_GUID(GUID_DEVINTERFACE_SampleDriver,\
0xc459a9ec, 0xb463, 0x4838, 0x9a, 0xd5,0xe0, 0x4a, 0x9a, 0xa2, 0xc4, 0xbe);
#define CharSample_IOCTL_800 CTL_CODE(FILE_DEVICE_UNKNOWN,0x800, METHOD_BUFFERED, FILE_ANY_ACCESS)
其中GUID_DEVINTERFACE_SampleDriver,就是创建设备时,定义的设备接口。CharSample_IOCTL_800就是定义设备控制事件队列的
1.2 通过设备接口查询设备路径
PCHAR
GetDevicePath(
IN LPGUID InterfaceGuid
)
{
HDEVINFO HardwareDeviceInfo;
SP_DEVICE_INTERFACE_DATADeviceInterfaceData;
PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData= NULL;
ULONG Length, RequiredLength = 0;
BOOL bResult;
HardwareDeviceInfo = SetupDiGetClassDevs(
InterfaceGuid,
NULL,
NULL,
(DIGCF_PRESENT |DIGCF_DEVICEINTERFACE));
if (HardwareDeviceInfo ==INVALID_HANDLE_VALUE) {
printf("SetupDiGetClassDevsfailed!\n");
exit(1);
}
DeviceInterfaceData.cbSize =sizeof(SP_DEVICE_INTERFACE_DATA);
bResult =SetupDiEnumDeviceInterfaces(HardwareDeviceInfo,
0,
InterfaceGuid,
0,
&DeviceInterfaceData);
if (bResult == FALSE) {
/*
LPVOID lpMsgBuf;
if(FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,
0,
NULL
)) {
printf("Error: %s",(LPSTR)lpMsgBuf);
LocalFree(lpMsgBuf);
}
*/
printf("SetupDiEnumDeviceInterfaces failed.\n");
SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
exit(1);
}
SetupDiGetDeviceInterfaceDetail(
HardwareDeviceInfo,
&DeviceInterfaceData,
NULL,
0,
&RequiredLength,
NULL
);
DeviceInterfaceDetailData =(PSP_DEVICE_INTERFACE_DETAIL_DATA) LocalAlloc(LMEM_FIXED, RequiredLength);
if (DeviceInterfaceDetailData == NULL) {
SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
printf("Failed to allocatememory.\n");
exit(1);
}
DeviceInterfaceDetailData->cbSize =sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
Length = RequiredLength;
bResult = SetupDiGetDeviceInterfaceDetail(
HardwareDeviceInfo,
&DeviceInterfaceData,
DeviceInterfaceDetailData,
Length,
&RequiredLength,
NULL);
if (bResult == FALSE) {
/*
LPVOID lpMsgBuf;
if(FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
(LPSTR) &lpMsgBuf,
0,
NULL
)) {
MessageBox(NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK);
LocalFree(lpMsgBuf);
}
*/
printf("Error inSetupDiGetDeviceInterfaceDetail\n");
SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
LocalFree(DeviceInterfaceDetailData);
exit(1);
}
returnDeviceInterfaceDetailData->DevicePath;
}
1.3 打开设备
CreateFile这里的路径需要填写设备路径,可以通过上面的函数查到,也可以自己直接指定。
1.4 DeviceIoControl控制设备
// Call device IO Control interface(CharSample_IOCTL_800) in driver
if (!DeviceIoControl(hDevice,
CharSample_IOCTL_800,
bufInput,
1,
bufOutput,
2,
&nOutput,
NULL)
)
{
printf("ERROR:DeviceIoControl returns %0x.", GetLastError());
goto exit;
}
说明下: 这里的CharSample_IOCTL_800就是在设备事件队列中定义的驱动IO控制功能
1.5 CloseHandle(hDevice)
最后关闭设备就可以了