请看下面这个#####################################################:
首先我们先来看几段最简单的代码:
这是定义了的一个参数结构:
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));
}
...
}
再然后呢,我们在应用程序中调用该驱动:
....
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))这语句能否正确输出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));
}
...
}
经历这么一次转换之后,应用程序调用驱动就能正常输出了。