Is there a way to forward-declare the HINSTANCE
type from the WinAPI without including the full (and big) windows.h
header?
For example, if I have a class RenderWindow
which owns an HINSTANCE mInstance
, i will have to include windows.h
in RenderWindow.h
. So everything that needs RenderWindow
also has to include windows.h
.
I tried including windef.h
but this seems to need some things from windows.h
. :-( If I can't forward declare it, is there at least a portable way to use s开发者_如何学Goomething like long mInstance
in RenderWindow
instead of HINSTANCE
?
HINSTANCE is declared in WinDef.h as typedef HINSTANCE__* HINSTANCE;
You may write in your headers:
#ifndef _WINDEF_
class HINSTANCE__; // Forward or never
typedef HINSTANCE__* HINSTANCE;
#endif
You will get compilation errors referencing a HINSTANCE when WinDef.h is not included.
You could declare it void* and cast the errors away. This is close to a never-ending battle though, sooner or later you'll get tripped up. Use pre-compiled headers so you don't care about the size of windows.h
stdafx.h:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
For example, if I have a class
RenderWindow
which owns anHINSTANCE mInstance
, i will have to includewindows.h
inRenderWindow.h
. So everything that needsRenderWindow
also has to includewindows.h
.
Have you looked at the Pimpl idiom? This allows you to hide private members. A side-effect is that you don't have to include their headers in your class' header.
Hey @NoSenseEtAl I guess we are still there.
In 2021, HINSTANCE
is defined in <minwindef.h>
. Including directly <minwindef.h>
gives the error: "No Target Architecture"
To work around the error, do the following (assuming building for x64):
#define _AMD64_
#include <minwindef.h>
int main() {
HINSTANCE h;
}
Note that the macro _AMD64_
is not documented, it starts with underscore, so not to be defined by user.
And it is defined only by <Windows.h>
, so there's no smaller header to include make it defined.
Apparently there's more hope that Windows SDK will work fine with Modules, so can fix the build speed by Modules instead.
The best portable way to deal with handles without header including is reinterpret_cast
ing them to a type with exactly the same size.
Most handles have pointer size1. So void*
or uintptr_t
will do. Examples:
_beginthreadex
returnsuintptr_t
instead ofHANDLE
to a thread.- MSVC
thread::native_handle
returnsvoid*
Be sure to static_assert
for type sizes in a place where you see the type.
1 Few handles don't have pointer size, I can only recall the one returned by AcquireCredentialsHandle
.
精彩评论