//========================================================================
//TITLE:
// DeviceIoControl和结构体内嵌指针
//AUTHOR:
// norains
//DATE:
// Thursday 21-August-2008
//Environment:
// NONE
//========================================================================
首先我们先来看几段最简单的代码:
这是定义了的一个参数结构:
typedef struct _DEV_Param
{
UNCHAR DeviceAddr;
UNCHAR nWriteByte;
UNCHAR *pWriteBuffer;
UNCHAR nReadByte;
UNCHAR *pReadBuffer;
} DEV_Param;
接下来这是驱动里面的响应DeviceIoControl的函数:
BOOL DEV_IOControl( DWORD hOpenContext, DWORD dwCode, PBYTE pBufIn, DWORD dwLenIn, PBYTE pBufOut, DWORD dwLenOut, PDWORD pdwActualOut )
{
....
DEV_Param *pDEV_Param = (DEV_Param *)pBufIn;
for(int i = 0; i < pDEV_Param->nWriteByte; i++)
{
RETAILMSG(TRUE,(TEXT("Write code is [%x]/n"),pDEV_Param->pWriteBuffer[i]));
}
...
}
再然后呢,我们在应用程序中调用该驱动:
....
DEV_Param param = {0};
UNCHAR szBuf[20] = {0x10,0x20,0x30};
param.nWriteByte = 20;
param.pWriteBuffer = szBuf;
...
DeviceIoControl(hd,IOCTL_WRITE,¶m,sizeof(param),NULL,NULL,NULL);
...
如果我说,RETAILMSG(TRUE,(TEXT("Write code is [%x]/n"),pDEV_Param->pWriteBuffer[i]))这语句能否正确输出pWriteBuffer里面的数值,取决于应用程序的szBuf的定义:比方说,当szBuf为局部变量,就能正常输出;如果为static或全局变量,输出就不正常,你会不会觉得奇怪?
没办法,但事实确实如此。因为这涉及到驱动的安全问题。其实我们在传递param时,系统已经对其地址做了一次转换。另一方面,因为系统并不知道你传过来的是内嵌有指针的结构体,所以需要自己动手进行转换。
因此,我们只需要在驱动中手工调用一次MapCallerPtr函数进行转换即可:
BOOL DEV_IOControl( DWORD hOpenContext, DWORD dwCode, PBYTE pBufIn, DWORD dwLenIn, PBYTE pBufOut, DWORD dwLenOut, PDWORD pdwActualOut )
{
....
DEV_Param *pDEV_Param = (DEV_Param *)pBufIn;
if(pDEV_Param->pWriteBuffer != NULL)
{
pDEV_Param->pWriteBuffer = (UCHAR *)MapCallerPtr((VOID *)pDEV_Param->pWriteBuffer,pDEV_Param->nWriteByte);
}
if(pDEV_Param->pReadBuffer != NULL)
{
pDEV_Param->pReadBuffer = (UCHAR *)MapCallerPtr((VOID *)pDEV_Param->pReadBuffer,pDEV_Param->nReadByte);
}
for(int i = 0; i < pDEV_Param->nWriteByte; i++)
{
RETAILMSG(TRUE,(TEXT("Write code is [%x]/n"),pDEV_Param->pWriteBuffer[i]));
}
...
}
经历这么一次转换之后,应用程序调用驱动就能正常输出了。
DeviceIoControl 传送自定义结构数据
最新推荐文章于 2021-08-03 14:04:42 发布