简易OBJECT管理

#pragma pack(push, 0x10)
typedef struct _MM_OBJECT_HEADER
{
	LONG RefCount;
	BOOL AutoDelete;
}MM_OBJECT_HEADER, *PMM_OBJECT_HEADER;
#pragma pack(pop)
/*
若使用MmCreateObject(TRUE)创建对象
当无引用时MmDerefObject自动释放内存
否则需要手动调用MmDeleteObject
*/
template <class T>
FORCEINLINE
T* MmCreateObject(BOOL IsAutoDelete = FALSE)
{
	PMM_OBJECT_HEADER ObjectHeader;

	ObjectHeader = (PMM_OBJECT_HEADER)MyHeapAlloc(sizeof(MM_OBJECT_HEADER) + sizeof(T));
	ObjectHeader->RefCount = 1;
	ObjectHeader->AutoDelete = IsAutoDelete;
	return (T*)(ObjectHeader + 1);
}

FORCEINLINE
VOID MmDeleteObject(PVOID Object)
{
	PMM_OBJECT_HEADER ObjectHeader;

	ObjectHeader = (PMM_OBJECT_HEADER)((PCHAR)Object - sizeof(MM_OBJECT_HEADER));
	if (ObjectHeader->RefCount != 0)
		RaiseException(ERROR_INVALID_OPERATION, 0, 0, NULL);
	MyHeapFree(ObjectHeader);
}

FORCEINLINE
VOID MmRefObject(PVOID Object)
{
	PMM_OBJECT_HEADER ObjectHeader;

	ObjectHeader = (PMM_OBJECT_HEADER)((PCHAR)Object - sizeof(MM_OBJECT_HEADER));
	if (ObjectHeader->RefCount <= 0)
		RaiseException(ERROR_INVALID_OPERATION, 1, 0, NULL);
	InterlockedIncrement(&ObjectHeader->RefCount);
}

FORCEINLINE
BOOL MmDerefObject(PVOID Object)
{
	PMM_OBJECT_HEADER ObjectHeader;

	ObjectHeader = (PMM_OBJECT_HEADER)((PCHAR)Object - sizeof(MM_OBJECT_HEADER));
	if (ObjectHeader->RefCount < 1)
		RaiseException(ERROR_INVALID_OPERATION, 2, 0, NULL);
	if (InterlockedDecrement(&ObjectHeader->RefCount) == 0)
	{
		if (ObjectHeader->AutoDelete)
		{
			MmDeleteObject(Object);
		}
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

FORCEINLINE
LONG MmGetObjectRefCount(PVOID Object)
{
	PMM_OBJECT_HEADER ObjectHeader;

	ObjectHeader = (PMM_OBJECT_HEADER)((PCHAR)Object - sizeof(MM_OBJECT_HEADER));
	return ObjectHeader->RefCount;
}

你可能感兴趣的:(简易OBJECT管理)