驱动编程——字符串与链表

字符串操作

字符串初始化

1
2
UNICODE_STRING str = {0};
RtlInitUnicodeString(&str, L"my first string");

字符串拷贝

1
2
3
4
5
6
7
UNICODE_STRING dst; //目标字符串
WCHAR dst_buf[256]; //我们现在还不会分配内存,就定义固定长度的缓冲区吧
UNICODE_STRING src = RTL_CONSTANT_STRING(L"my first string");

// 把目标字符串初始化为拥有缓冲区长度为0的UNICODE_STRING空串
RtlInitEmptyUnicodeString(&dst, dst_buf, 256*sizeof(WCHAR));
RtlCopyUnicodeString(&dst, &src); // 字符串拷贝

字符串连接

1
2
3
4
5
6
7
8
9
10
11
12
13
NTSTATUS status;
UNICODE_STRING dst; //目标字符串
WCHAR dst_buf[256]; //我们现在还不会分配内存,就定义固定长度的缓冲区吧
UNICODE_STRING src = RTL_CONSTANT_STRING(L"my first string");

// 把目标字符串初始化为拥有缓冲区长度为256*sizeof(WCHAR)的UNICODE_STRING空串
RtlInitEmptyUnicodeString(&dst, dst_buf, 256*sizeof(WCHAR));
RtlCopyUnicodeString(&dst, &src); // 字符串拷贝

status = RtlAppendStringToString(&dst, L"my second string");
//如果连接两个UNICODE_STRING
//The RtlAppendUnicodeStringToString routine concatenates two Unicode strings.
status = RtlAppendUnicodeStringToString(&dst, &another);

字符串打印

1
2
3
4
5
6
7
NTSTATUS
RtlStringCbPrintfW(
OUT LPWSTR pszDest,
IN size_t cbDest,
IN LPCWSTR pszFormat,
...
);

这个需要包含头文件ntsagestr.h

1
2
3
4
5
6
#include <ntsagestr.h>
......
......
status = RtlStringCbPrintfW(
dst->Buffer, 512*sizeof(WCHAR), L"filepath = %wz file size = %d \r\n",&file_path, file_size);
dst->Length = wcslen(dst->Buffer)*sizeof(WCHAR);

内存与链表

内存的分配与释放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
NTSTATUS status;
#define MEM_TAG 'MyTt'
// 目标字符串,接下来为它分配空间
UNICODE_STRING dst;
UNICODE_STRING src = RTL_CONSTANT_STRING(L"my first string");
dst.Buffer = (PWCHAR)ExAllocatePoolWithTag(NonPagedPool, src.Length, MEM_TAG);
if (dst.Buffer == NULL)
{
/* 错误处理 */
status = STATUS_INSUFFICIENT_RESOURCES;
}
dst.Length = dst.MaximumLength = src.Length;
RtlCopyUnicodeString(&dst, &src);

ExFreePool(dst.Buffer);
dst.Buffer = NULL;
dst.Length = dst.MaximumLength = 0;

使用LIST_ENTRY

使用长长整形数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#if defined(MIDL_PASS)
typedef struct _LARGE_INTEGER {
#else // MIDL_PASS
typedef union _LARGE_INTEGER {
struct {
DWORD LowPart;
LONG HighPart;
};
struct {
DWORD LowPart;
LONG HighPart;
} u;
#endif //MIDL_PASS
LONGLONG QuadPart;
} LARGE_INTEGER;

自旋锁

初始化

1
2
KSPIN_ my_Spin_Lock;  
KeInitializeSpinLock(&my_Spin_Lock);

使用

1
2
3
4
5
6
7
8
9
10
11
void MySafeFunction()  
{
KSPIN_LOCK my_spin_lock;
KIRQL irql;
KeInitialiezeSpinLock(&my_spin_lock);
KeAccquireSpinLock(&my_spin_lock, &irql);

//----do something

KeReleaseSpinLock(&my_spin_lock, &irql);
}
自愿打赏专区