Windows驱动4. 常用数据类型
Windows驱动4. 常用数据类型
字符串
在驱动中, 字符串并不建议使用C中的Ascii字符串或者C++中的std::string, 而是使用 UNICODE_STRING 结构体作为字符串
c
typedef struct _UNICODE_STRING {
USHORT Length; //有效字符串的长度(字节数)
USHORT MaximumLength; //字符串的最大长度(字节数)
PWSTR Buffer; //指向字符串的指针
}UNICODE_STRING,*PUNICODE_STRING;字符串的初始化
c
VOID StringDemo()
{
// 一个运行时计算常量字符串, 会被放在常量区, 不可修改和释放
UNICODE_STRING runtimeReadonlyString = { 0 };
RtlInitUnicodeString(&runtimeReadonlyString, L"TestString");
KdPrint(("RuntimeReadonlyString: %wZ\n", &runtimeReadonlyString));
// 一个常量字符串, 不可修改和释放
UNICODE_STRING constString = RTL_CONSTANT_STRING(L"Const String");
KdPrint(("ConstString: %wZ\n", &constString));
// 一个栈上字符串, 但是数据放在堆里, 需要手动释放内存
UNICODE_STRING str1 = { 0 };
str1.Buffer = ExAllocatePool2(POOL_FLAG_NON_PAGED, sizeof(WCHAR) * 100, '1rts');
str1.MaximumLength = 100 * sizeof(WCHAR);
str1.Length = 0;
UNICODE_STRING str2 = RTL_CONSTANT_STRING(L"Hello");
UNICODE_STRING str3 = RTL_CONSTANT_STRING(L"World");
RtlAppendUnicodeStringToString(&str1, &str2);
RtlAppendUnicodeStringToString(&str1, &str3);
KdPrint(("Str1: %wZ\n", &str1));
ExFreePool(str1.Buffer);
// 一个栈字符串
UNICODE_STRING stackString = { 0 };
WCHAR stackBuffer[100] = L"Stack String";
RtlInitUnicodeString(&stackString, stackBuffer);
KdPrint(("Stack string: %wZ", &stackString));
// 一个堆字符串, 需要手动释放内存
UNICODE_STRING heapString;
RtlCreateUnicodeString(&heapString, L"Heap String");
KdPrint(("Heap string: %wZ", &heapString));
RtlFreeUnicodeString(&heapString);
}RtlInitUnicodeString 和 RtlCreateUnicodeString 的不同:
RtlInitUnicodeString(&str, source)仅仅初始化一个字符串, 不会分配内存, 它只会把内存地址赋值给source, 并计算字符串的长度和最大长度存入Length和MaximumLength中, 其生命周期由完全由source决定RtlCreateUnicodeString(&str, source)会分配内存, 并把source的内容拷贝到新分配的内存中, 需要手动调用RtlFreeUnicodeString释放内存
Warning | 调用 RtlInitUnicodeString 如果字符串是一个常量字符串, 则不需要手动释放内存, 否则会导致蓝屏 |
字符串的操作
| 函数 | 说明 |
|---|---|
RtlInitUnicodeString | 初始化字符串 |
RtlCreateUnicodeString | 创建字符串 |
RtlAppendUnicodeStringToString | 追加字符串 |
RtlCopyUnicodeString | 复制字符串 |
RtlEqualUnicodeString | 比较字符串 |
RtlFreeUnicodeString | 释放字符串 |
基础类型
基础类型尽量使用大写形式的类型, 在打印时其占位符如下:
| 类型 | 占位符 |
|---|---|
SHORT | %hd |
INT | %d |
LONG | %ld |
HEX | %x(小写) 或 %X(大写) |
char* | %s |
wchar_t* | %S |
ANSI_STRING | %Z |
UNICODE_STRING | %wZ |
Windows驱动4. 常用数据类型
https://simonkimi.githubio.io/2024/08/03/Windows驱动4-常用数据类型/