Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use std::unique_ptr to manage DLL resource?

Tags:

c++

c++11

dll

raii

I have many LoadLibrary in my project, and need to call FreeLibrary manually for each LoadLibrary. I want to use the std::unique_ptr with specific deleter to make it auto release my dll resource.

This is what I am trying to define:

std::unique_ptr<HMODULE, BOOL(*)(HMODULE)> theDll(LoadLibrary("My.dll"), FreeLibrary);

But the compiler complains the type does not match. I found out it expects *HMODULE from LoadLibrary. That is std::unique_ptr<A> will expect A* as its pointer type. It looks I still need to define a new class to manage DLL resource(LoadLibrary in constructor and FreeLibrary in destructor).

Is is possible to make std::unique_ptr<A> to just expect the A as its pointer type?

Updated,

The following is pros and cons for new class and using std::unique_ptr, summarized from the answers.

Create another dll management class,

pros:

  • Fully controllable to customize for DLL semantic.
  • Isolate the DLL related parts into a class with one responsibility.
  • Easy to extend if need more functionality for DLL like exposing symbol.

cons:

  • Need rebuild the RAII part what stadard auto pointer has been done.
  • Has chance to make mistake in RAII part.
  • Need Declare a new class.

Use std::unique_ptr with custom deleter,

pros:

  • No need to declare another a class.
  • Reuse the RAII part of unique_ptr.
  • Maybe the move semantics prevents DLL Module instance to be copied?

cons:

  • The Dll resource semantic may not fit the standard auto pointer, and error-prone?
  • The template parameter in unique_ptr is complex and hard to find where error is.
  • HMODULE is void*, a type-less type, may be a problem to integrate with unique_ptr?

Please correct me at comment if I am wrong.

like image 934
Chen OT Avatar asked Jul 29 '15 06:07

Chen OT


1 Answers

According to this page, HMODULE is HINSTANCE, HINSTANCE is HANDLE, HANDLE is PVOID, and PVOID is void *. Which means that HMODULE is a pointer type. So the following should work:

std::unique_ptr<std::remove_pointer_t<HMODULE>, BOOL(*)(HMODULE)> theDll(LoadLibrary("My.dll"), FreeLibrary);
like image 54
Nikolai Avatar answered Oct 24 '22 21:10

Nikolai