RAII in kernel mode drivers

The (kernel mode) audio driver I’ve been working on has lots of clutter/complexity due to lack of any RAII class use. In order to ensure single-entry single-exit (SESE), there’s copious use of preprocessor macros containing goto. The code is also filled with explicit calls to IUnknown->Release() and other pairs of allocate/deallocate type functions.

I’ve been itching to look into replacing all the ISomeType pointers with _com_ptr_t<ISomeType>, but having read through a really long thread here about C vs C++ in kernel mode drivers (among other threads), I looked at the _com_ptr_t type (as defined in the standard Windows header files) and confirmed that it does indeed use exceptions.

Then I ran across a Microsoft header-only C++ library called Windows Implementation Libraries (WIL):

The Windows Implementation Libraries (WIL) is a header-only C++ library created to make life easier
for developers on Windows through readable type-safe C++ interfaces for common Windows coding patterns.

Some things that WIL includes to whet your appetite:

- Smart pointers and auto-releasing resource wrappers...

A quick glance at the com_ptr_t type there seems to indicate that they don’t use exceptions (unless you define a preprocessor symbol to indicate that you want them. WIL is clearly not designed exclusively for the kernel environment; e.g. it includes types to wrap window handles and other stuff that only applies to user mode.

Still, I’m wondering whether anyone has used (or looked into using) WIL types in kernel code?

1 Like

I don’t know about WIL, but there’s no reason you can’t use smart pointers (std::unique_ptr, for example) or auto storage class instances (so called “instantiated on the stack”) to rid yourself of the mess.

That’s what I do (in the rare case I need to do tear down more complex than ExFreePool).

Peter

1 Like

…there’s no reason you can’t use smart pointers (std::unique_ptr, for example)

Good point. I saw contradictory statements (in the long C vs C++ post) saying std::unique_ptr was/wasn’t OK to use in kernel code, so I hadn’t looked into it yet.

I can write the trivial RAII wrappers for some things, but I wouldn’t attempt anything with all the complex behavior of _com_ptr_t<T>, and that’s what I’d be using most frequently.

Remember that _com_ptr_t is actually a Microsoft compiler extension, and requires a backing library that might not be kernel-compatible. You can certainly create your own wrapper, similar to ATL’s CComPtr. That has no special compiler support.

Remember that _com_ptr_t is actually a Microsoft compiler extension…

I had no idea that was the case.