将可变长度结构从用户模式传递到内核模式

时间:2013-04-26 00:02:12

标签: c windows drivers wdk

我正在编写虚拟磁盘驱动程序,我的结构定义如下:

typedef struct _MOUNT_NEW_QUERY {
    PWCHAR imagePath;
    WCHAR letter;
    PCHAR key;
} MOUNT_NEW_QUERY, *PMOUNT_NEW_QUERY;

所以我有一些动态大小的结构。

我如何将它从用户模式传递给我的驱动程序?

1 个答案:

答案 0 :(得分:2)

分配一个连续的内存块,足以容纳你的结构和“key”和“path”的数据 - 就像这样:

/* we add + 1 for terminating NULLs to make life easy */
size_t keyLen = (strlen(key) +  1); 
size_t imgLen = (wcslen(imagePath) + 1) * sizeof(WCHAR);

PMOUNT_NEW_QUERY pMNQ = malloc(sizeof(MOUNT_NEW_QUERY) + keyLen + imgLen);

if(pMNQ != NULL) 
{       
   /* make imagePath point to the allocated buffer immediately after 
    * the MOUNT_NEW_QUERY portion 
    */
   pMNQ->imagePath = (PWCHAR)((PBYTE)pMNQ + sizeof(MOUNT_NEW_QUERY));

   /* make the key point to the allocated buffer immediately after 
    * the imagePath portion (including a NULL WCHAR terminator)
    */
   pMNQ->key = (PCHAR)((PBYTE)pMNQ + sizeof(MOUNT_NEW_QUERY) + imgLen);

   /* populate the data here appropriately, typically with strcpy
    * and wcscpy, and then send the IOCTL 
    */
   fun(pMNQ);
}

当您为驱动程序调用IOCTL时,请传递缓冲区的大小,而不仅仅是MOUNT_NEW_QUERY结构的大小。

相关问题