Proper way close WinAPI HANDLEs (avoiding of repeated closing) - c++

I have some handle and I need to close it. There is some places in code, where handle may be closed. So, is this a right way to close handle?
HANDLE h;
....
if ( h != INVALID_HANDLE_VALUE ) {
::CloseHandle(h);
h = INVALID_HANDLE_VALUE;
}
There is a same question about bitmap handles:
HBITMAP hb;
....
if ( hb != INVALID_HANDLE_VALUE ) {
::DeleteObject(hb);
hb = INVALID_HANDLE_VALUE;
}
EDIT: I think, there is some misunderstanding. I know CloseHandle is for closing handles. I'd like to know proper way for closing handles. A similar situations occurs with deleting of pointers.
Foo *foo = new Foo();
// for example there is 2 functions that can delete foo
void bar() {
....
delete foo;
}
void duck() {
....
delete foo;
}
So, the following code means problems:
bar();
duck();
There is some workaround for this case. We need to define bar&duck functions like this:
void bar() {
....
if (foo) {
delete foo;
foo = NULL;
}
}
void duck() {
....
if (foo) {
delete foo;
foo = NULL;
}
}
So we avoid repeated deleting of foo. The question is What is the proper way to close handles? I mean, How to avoid repeated closing handles problem?

Not all functions that use HANDLE use CloseHandle(), some use other closing functions instead. Also, not all HANDLE values use INVALID_HANDLE_VALUE, either. Some use NULL instead.
HBITMAP never uses INVALID_HANDLE_VALUE, it always uses NULL. And you should never call DeleteObject() for an HBITMAP you do not own.
So the short answer is - if you are trying to create some general purpose handle management, don't bother. You are likely to get it wrong. If you allocate/open some handle, you have to know the correct way to close it, you can't guess at it.
If you want the handles to manage themselves, then RAII is the best choice. I prefer to use a templated class with specialized traits to reduce code duplication for differrent types of handles, eg:
template< class traits >
class HandleWrapper
{
private:
traits::HandleType FHandle;
public:
HandleWrapper()
FHandle(traits::InvalidValue)
{
}
HandleWrapper(const traits::HandleType value)
FHandle(value)
{
}
~HandleWrapper()
{
Close();
}
void Close()
{
if (FHandle != traits::InvalidValue)
{
traits::Close(FHandle);
FHandle = traits::InvalidValue;
}
}
bool operator !() const {
return (FHandle == traits:::InvalidValue);
}
operator bool() const {
return (FHandle != traits:::InvalidValue);
}
operator traits::HandleType() {
return FHandle;
}
};
.
struct KernelHandleTraits
{
typedef HANDLE HandleType;
static const HANDLE InvalidValue = INVALID_HANDLE_VALUE;
static void Close(HANDLE value)
{
CloseHandle(value);
}
};
HandleWrapper<KernelHandleTraits> hFile(CreateFile(...));
.
struct NullKernelHandleTraits
{
typedef HANDLE HandleType;
static const HANDLE InvalidValue = NULL;
static void Close(HANDLE value)
{
CloseHandle(value);
}
};
HandleWrapper<NullKernelHandleTraits> hMapping(CreateFileMapping(...));
.
struct FileMapViewTraits
{
typedef void* HandleType;
static const void* InvalidValue = NULL;
static void Close(void *value)
{
UnmapViewOfFile(value);
}
};
HandleWrapper<FileMapViewTraits> hView(MapViewOfFile(...));
.
struct GDIBitmapHandleTraits
{
typedef HBITMAP HandleType;
static const HBITMAP InvalidValue = NULL;
static void Close(HBITMAP value)
{
DeleteObject(value);
}
};
HandleWrapper<GDIBitmapTraits> hBmp(CreateBitmap(...));
Etc.

Use RAII pattern.
Wrap a handle into a class which allocates the handle in the constructor and destroys it in the destructor. You can find some examples in MFC, e.g. CGdiObject class for GDI objects like HBITMAP.
See also this SO question: RAII and smart pointers in C++

Yes.
CloseHandle() closes windows kernel object handles.
DeleteObject() deletes GDI objects.
I think your confusion comes from them both being called "handles", but they are different "classes" of objects. The term handle in HBITMAP is used here more as "opaque identifier". There is also plenty of documentation which assumes "handle" == "windows kernel handle".
In general if you're wondering how to delete something you should look at the constructor's documentation.

The following code is maybe what you're after:
BOOL CloseValidHandle(HANDLE& handle)
{
if (handle != INVALID_HANDLE_VALUE && handle != 0)
{
if (CloseHandle(handle))
{
handle = INVALID_HANDLE_VALUE;
return TRUE;
}
else
{
return FALSE;
}
}
return TRUE;
}

It's no RAII but it helps to delete/close handler.
class HandleDel : boost::notcopyable{
public:
HandleDel(HANDLE h, HANDLE invalid, BOOL(WINAPI *del)(HANDLE)):
h(h), invalid(invalid), del(del){
}
~HandleDel(){
if ( h != invalid ) del(h);
}
private:
HANDLE h;
HANDLE invalid;
BOOL(WINAPI *del)(HANDLE);
};

Related

When should we use a custom deleter instead of the default deleter in a unique_ptr?

I couldn't understand, if there is already a default deleter in unique_ptr, then what is the need of using a custom deleter?
Could anyone explain this by giving a simple example?
I use custom deletes to quickly wrap C-API, for example to help me with OpenSSL:
namespace helper {
template<typename T>
struct Deleter;
template<>
struct Deleter<::BIO>
{
void operator()(::BIO* p) const
{
// result used during debugging
[[maybe_unused]] auto result = BIO_free(p);
}
};
template<>
struct Deleter<::X509>
{
void operator()(::X509* p) const
{
X509_free(p);
}
};
template<>
struct Deleter<::PKCS12>
{
void operator()(::PKCS12* p) const
{
PKCS12_free(p);
}
};
template<>
struct Deleter<::EVP_PKEY>
{
void operator()(::EVP_PKEY* p) const
{
EVP_PKEY_free(p);
}
};
template<>
struct Deleter<STACK_OF(X509)>
{
void operator()(STACK_OF(X509) * p) const
{
sk_X509_pop_free(p, X509_free);
}
};
template<>
struct Deleter<STACK_OF(GENERAL_NAME)>
{
void operator()(STACK_OF(GENERAL_NAME) * p) const
{
sk_GENERAL_NAME_free(p);
}
};
template<>
struct Deleter<GENERAL_NAME>
{
void operator()(GENERAL_NAME* p) const
{
GENERAL_NAME_free(p);
}
};
template<typename T, typename D = Deleter<T>>
std::unique_ptr<T, D> wrapUnique(T* p, D deleter = {})
{
return std::unique_ptr<T, D>{p, deleter};
}
}
And I use other helper functions to make use OpenSSL more C++sy.
This is especially handy when handling errors (since release of resources is painless in such case).
Here is an example of using std::unique_ptr to manage an old C style FILE* in RAII style.
The deleter will close the file automatically when the std::unique_ptr will attempt to release the managed resource.
This is useful e.g. if you have some legacy code using FILE* file(s) and you would like to avoid manually managing closing them.
#include <iostream>
#include <memory>
struct FileDeleter
{
void operator()(FILE* pFile)
{
if (pFile)
{
std::cout << "closing file ...\n";
fclose(pFile);
}
}
};
using FileUniquePtr = std::unique_ptr<FILE, FileDeleter>;
int main()
{
{
// Getting a FILE* from legacy code:
FILE* pFile = nullptr;
std::cout << "opening file ...\n";
auto err = fopen_s(&pFile, "aaa.txt", "r");
if (err != 0)
{
// Handle error ...
return -1;
}
// New C++ code:
FileUniquePtr filePtr{ pFile };
// Do something with the file via filePtr ...
} // Here filePtr goes out of scope and the deleter will be called and close the file automatically.
}
Output:
opening file ...
closing file ...
The default deleter is ok if doing delete over the pointer wrapped by unique_ptr is the correct thing to do to dispose of it. That is ok if your pointer comes from new, but it's not correct in many other situations.
A simple example is FILE *: a FILE * is a pointer that cannot be deleted with delete, but instead you have to use fclose on it. Using a custom deleter it's very easy to wrap it in a unique_ptr and let it take care of destruction/move/...:
namespace detail {
struct file_ptr_deleter {
void operator() (FILE *fp) {
if(fp) fclose(fp);
}
};
}
/// RAII-style wrapper for a FILE*
struct unique_c_file : std::unique_ptr<FILE, detail::file_ptr_deleter> {
using std::unique_ptr<FILE, detail::file_ptr_deleter>::unique_ptr;
operator FILE *() { return get(); }
};
(in this case I even inherited from std::unique_ptr to ease the use of unique_c_file directly in C APIs).
Other, possibly more common cases, are if you have memory that comes from libraries, that provide their own function to delete it; for example, you may use BSD sockets, where getaddrinfo provides you an addrinfo * that must be freed using freeaddrinfo; even in this case, it's easy to create a smart pointer for that:
namespace detail {
struct addrinfo_deleter {
void operator()(addrinfo *elem) {
if(elem) freeaddrinfo(elem);
}
};
}
/// unique_ptr to handle an %addrinfo linked list provided by %getaddrinfo
typedef std::unique_ptr<addrinfo, detail::addrinfo_deleter> addrinfo_ptr;
Similarly in Win32 programming where many APIs provide you memory that has been allocated with LocalAlloc and thus must be freed with LocalFree:
// Custom deleter (for unique_ptr) using Win32 LocalFree
struct LocalFree_deleter { void operator()(void *ptr) { LocalFree(ptr); } };
// ...
std::unique_ptr<LPWSTR[], LocalFree_deleter> argvw(CommandLineToArgvW(cmdline_u16, &argc));
You can even go a step further, and work with stuff that aren't even pointers, but opaque "handles": again in Win32 this is quite common, and there are even different types of handles require different closing functions; even in this case, unique_ptr and custom deleters to the rescue:
template<decltype(CloseHandle) ch_fn = CloseHandle>
struct handle_deleter {
typedef HANDLE pointer;
void operator()(HANDLE obj) {
if(obj != NULL && obj != INVALID_HANDLE_VALUE) ch_fn(obj);
}
};
using unique_handle = std::unique_ptr<HANDLE, handle_deleter<>>;
using unique_find_handle = std::unique_ptr<HANDLE, handle_deleter<FindClose>>;
notice that here handle_deleter provided a typedef HANDLE pointer: this typedef is used by unique_ptr as the type that it stores in its bowels, returns in get() & co.

Converting different classes to void* and back safely in C++

I have a map of callbacks that pass information and execute various functions throughout code, very much like events in C# but in C++.
The map is defined as
std::map<std::string, std::function<void(uint8_t*)>> mCallbacks
It is passed by reference to all subprograms
Then each class binds its callbacks as such
mCallbacks["Status_Label"] = std::bind(&MenuHandler::LabelEditCallback, this, std::placeholders::_1);
Where
bool MenuHandler::LabelEditCallback(uint8_t * m_label_data)
{
int text_size = ((int*)m_label_text)[0];
char* v_text = (char*)&m_label_text[1];
}
And each event gets called from a different subprogram like this:
if (mCallbacks.find("Status_Label") != mCallbacks.end())
mCallbacks.at("Status_Label")((uint8_t*)selected_text);
This makes it easy to pass data and events around the program without making a mess of objects and references
As you can see, this is extremely unsafe, and converting from a uint8_t pointer to various data formats can easily lead to corrupted stack.
The problem is, I don't have a specific structure for callback arguments, some of them may be sending text data, others may be sending numbers.
My solution is to define structs that will be cast to void* when calling the event, and back in the callback function
Something like this (untested):
struct Label_Callback_Data
{
Label_Callback_Data(std::string v_name, std::string v_text)
{
labelName = v_name;
labelText = v_text;
size_of = sizeof(this);
}
int size_of;
std::string labelName;
std::string labelText;
};
And I would call it like this:
if (mCallbacks.find("Status_Label") != mCallbacks.end())
mCallbacks.at("Status_Label")((uint8_t*)Label_Callback_Data("Status_Label_name", "TEXT"))
But then how would I recover it here? If I dont know the exact size of the object?
bool MenuHandler::LabelEditCallback(uint8_t * m_label_data)
{
//?? Label_Callback_Data text_size = (Label_Callback_Data*)m_label_text
}
One solution is to use object with fixed size arrays, but there has to be a C++11 solution that is safe to use, maybe something using dynamic_pointer_casts?
Also, as a bonus question, how would I know if the object passed to the callback function is smaller in size than it is expecting? Is it possible to check this and just return a false from the callback function so the program doesn't crash?
Thank you,
This code is not tested, so there may be logical mistakes I'm willing to correct per responses.
You should generally prefer to use a lambda instead of std::bind().
Try something more like this:
std::map<std::string, std::function<void(void*)>> mCallbacks;
struct Label_Callback_Data
{
std::string labelName;
std::string labelText;
Label_Callback_Data(std::string v_name, std::string v_text)
: labelName(v_name), labelText(v_text) { }
};
...
mCallbacks["Status_Label"] = [this](void *data){ this->LabelEditCallback(data); };
...
auto iter = mCallbacks.find("Status_Label");
if (iter != mCallbacks.end())
{
Label_Callback_Data data("Status_Label_name", "TEXT");
iter->second(&data);
}
...
bool MenuHandler::LabelEditCallback(void *m_label_data)
{
Label_Callback_Data *data = static_cast<Label_Callback_Data*>(m_label_text);
// use data->labelName and data->labelText as needed...
}
Alternatively, you could move the type-cast into the lambda itself, so LabelEditCallback() doesn't need to deal with void* at all:
std::map<std::string, std::function<void(void*)>> mCallbacks;
struct Label_Callback_Data
{
std::string labelName;
std::string labelText;
Label_Callback_Data(std::string v_name, std::string v_text)
: labelName(v_name), labelText(v_text) { }
};
...
mCallbacks["Status_Label"] = [this](void *data){ this->LabelEditCallback(static_cast<Label_Callback_Data*>(data)); };
...
auto iter = mCallbacks.find("Status_Label");
if (iter != mCallbacks.end())
{
Label_Callback_Data data("Status_Label_name", "TEXT");
iter->second(&data);
}
...
bool MenuHandler::LabelEditCallback(Label_Callback_Data *m_label_data)
{
// use m_label_data->labelName and m_label_data->labelText as needed...
}
This is how I did it
...
//The container
std::map<std::string, std::function<void(std::shared_ptr<CallbackData::BlankData>)>> mCallbacks
...
//CALLBACK FUNCTION
bool InputManager::KeyboardCallback(std::shared_ptr<CallbackData::BlankData> callback_data)
{
std::shared_ptr<CallbackData::Keyboard> keyboard_data = std::dynamic_pointer_cast<CallbackData::Keyboard>(callback_data);
if (keyboard_data == nullptr)
return false;
///...
}
...
//CALLBACK EVENT
if (mCallbacks.find("Keyboard") != mCallbacks.end())
{
std::shared_ptr<CallbackData::Keyboard> keyboard_data = std::make_shared<CallbackData::Keyboard>(m_keyboardState);
mCallbacks.at("Keyboard")(std::dynamic_pointer_cast<CallbackData::BlankData>(keyboard_data));
}
...
//Data structure
namespace CallbackData
{
struct BlankData
{
virtual ~BlankData() {};
};
struct Keyboard : public BlankData
{
Keyboard(uint8_t* kb_data)
{
kbData = kb_data;
}
uint8_t* kbData;
};
}

std::vector of std::functions find

I have a vector populated with callback functions and I would like to check whether callback to the function already exists prior to adding it. I don't know whether it will even work bu so far it doesn't even compile.
vector<std::function<void(void*)>> _callbacks;
void Event::RegisterCallback(std::function<void(void*)> callback)
{
if (callback == NULL)
return;
vector<std::function<void(void*)>>::iterator it = std::find(_callbacks.begin(), _callbacks.end(), callback);
if (it == _callbacks.end())
{
_callbacks.push_back(callback);
}
else
{
//print error
throw;
}
}
This gives a compile error:
"Overload resolution selected deleted operator '=='" in alorithm(805). This is related to the find function call.
How do I get this to work and is it even going to compare function calls to the same method properly?
Thanks
As noted in the comments the simplest solution is to use default C-style function pointers as they support == operator in opposite to C++11 function which does not.
using func_type = void(*)();
vector<func_type> _callbacks;
void Event::RegisterCallback(func_type callback)
{
if (callback == nullptr)
return;
auto it = std::find(_callbacks.begin(), _callbacks.end(), callback);
if (it == _callbacks.end()) {
_callbacks.push_back(callback);
}
else {
throw;
}
}
void f() {};
void g() {};
/*
evt.RegisterCallback(f); // works fine
evt.RegisterCallback(g); // works fine
evt.RegisterCallback(f); // throws exception
*/
If you don't like this approach you can write your own function-pointer class with support of equality operator.
Another solution is to have a class with a std::function member and another comperable member, and then overloading the () to get the std::function parameter and call it with the parameter, and the == operator to compeare the class using the comperable member.
CompareableFunction.h:
class CompareableFunction
{
public:
CompareableFunction(int nId, std::function<void(parameter)> handler);
~CompareableFunction();
void operator()(parameter param);
bool operator== (CompareableFunction compareableFunc);
private:
std::function<void(parameter)> m_handler;
int m_nId;
};
CompareableFunction.cpp:
CompareableFunction::CompareableFunction(int nId, std::function<void(parameter)> handler)
{
m_nId = nId;
m_handler = handler;
}
CompareableFunction::~CompareableFunction()
{
}
void CompareableFunction::operator()(parameter param)
{
return m_handler(param);
}
bool CompareableFunction::operator==(CompareableFunction compareableFunc)
{
return (m_nId == compareableFunc.m_nId);
}
EDIT: you can convert the std::function to a C-style function pointer and use it to compare. example to a conversion is here: http://www.cplusplus.com/forum/general/63552/

FunktionPointerArray in Singleton

I try to implement an array of function pointers in an singleton owning a thread.
In the thread function I get an error, telling me that a member has to be relative to an object. More in the commentline...
Header:
typedef struct{
int action;
HWND handle;
}JOB;
class Class{
public:
enum Action { 1,2 };
private:
JOB m_currentJob;
queue<JOB> Jobs;
static DWORD WINAPI ThreadFunction(LPVOID lpParam);
void (Class::*ftnptr[2])(JOB Job);
void Class::ftn1(JOB Job);
void Class::ftn2(JOB Job);
// Singleton pattern
public:
static Class* getInstance(){
if(sInstance == NULL)
sInstance = new Class();
return sInstance;
}
private:
Class(void);
~Class(void);
static Class* sInstance;
};
Body:
#include "Class.h"
Class* Class::sInstance = NULL;
Class::Class(){
this->ftnptr[0] = &Class::ftn1;
this->ftnptr[1] = &Class::ftn2;
}
DWORD WINAPI Class::AutoplayerThreadFunction(LPVOID lpParam)
{
Class *pParent = static_cast<Class*>(lpParam);
while(true){
(pParent->*ftnptr[pParent->m_currentJob.action])(pParent->m_currentJob);
/* The line above causes the compiler error. Curious to me is that
* neither "pParent->m_currentJob" nor "pParent->m_currentJob" cause
* any problems, although they are members too like the ftnptr array.
*/
}
}
void Class::ftn1(JOB Job){}
void Class::ftn2(JOB Job){}
A call via getInstance from the SingletonPattern doesnt make it any better.
Any suggestions?
ftnptr is a member of Class. However, you access it directly. That is, pParent->*ftnptr[...] means "access the member of pParent designated by the pointer ftnptr[...]", but it doesn't imply that ftnptr too is a member of pParent.
The correct code is (pParent->*(pParent->ftnptr[...]))(...). But I would recommend extracting the array index expression from that:
auto fnptr = pParent->ftnptr[...];
(pParent->*fnptr)(...);
I think it might be how you declare your array of pointer-to-member-functions. (Edit: This wasn't what was wrong. I'm keeping this answer up anyway, because typedefs for function pointers can really make code cleaner, so I think this is good advice.)
Try using a typedef:
typedef void (Class::*ftnptr)(JOB Job);
ftnptr[2] fn_ptrs;
Then use it like so:
Class::Class(){
this->fn_ptrs[0] = &Class::ftn1;
this->fn_ptrs[1] = &Class::ftn2;
}
DWORD WINAPI Class::AutoplayerThreadFunction(LPVOID lpParam)
{
Class *pParent = static_cast<Class*>(lpParam);
while(true){
(pParent->*(pParent->fn_ptrs[pParent->m_currentJob.action]))(pParent->m_currentJob);
/* The line above causes the compiler error. Curious to me is that
* neither "pParent->m_currentJob" nor "pParent->m_currentJob" cause
* any problems, although they are members too like the ftnptr array.
*/
}
}

Making a class friend itself

EDIT: It looks like I'm completely misinformed. Please close this thread. Gah.
For the record, the following compiles and works:
class ForeverAlone
{
private:
int m_friends;
HANDLE m_handle;
public:
ForeverAlone()
{
m_handle = CreateThread(NULL, 0, &ForeverAlone::SadThread, reinterpret_cast<void*>(this), 0, NULL);
}
~ForeverAlone()
{
if (m_handle != NULL)
CloseHandle(m_handle);
}
protected:
static unsigned long WINAPI SadThread(void* param)
{
ForeverAlone* thisObject = reinterpret_cast<ForeverAlone*>(param);
// is there any way for me to access:
thisObject->m_friends;
}
};
Original question: I have a static protected thread method, which I pass an object to. Can I somehow make the class friend itself so I can access its private members?
All class methods, static or not, are automatically "friends" of the class. Friend is used to allow external functions and classes access to a class. The class is always its own "friend".
Do this:
extern "c" DWORD __stdcall CInterfaceSadThread(LPVOID lpThreadParameter);
class ForeverAlone
{
private:
int m_friends;
HANDLE m_handle;
public:
ForeverAlone()
{
m_handle = CreateThread(NULL, 0,
&CInterfaceSadThread,
//
// You may get arguments about using static_cast here
// I still prefer reinterpret_cast as it makes it stick out
// Thus I check it more carefully when I see it.
// For this situation it works correctly
// As casting to void* and back to the original are guaranteed.
reinterpret_cast<void*>(this),
0, NULL);
}
~ForeverAlone()
{
if (m_handle != NULL)
CloseHandle(m_handle)
}
protected:
friend DWORD CInterfaceSadThread(LPVOID lpThreadParameter);
DWORD WINAPI SadThread()
{
// Do Stuff here
// Note: Just because you get here does not mean that the object is finished
// initializing. The parent thread may have been suspended after this
// one was created. Thus checking the state of member variables at this
// point is dangerous unless you can guarantee that construction has finished
return result;
}
};
Then in the callback just access your function;
extern "c" DWORD __stdcall CInterfaceSadThread(LPVOID lpThreadParameter)
{
// Note: You can only cast back to ForeverAlone* so be carefull
// Hence I use reinterpret_cast as this forces me to double check.
ForeverAlone* alone = reinterpret_cast<ForeverAlone*>(lpThreadParameter);
return alone->SadThread();
}