I'm designing an interface to abstract the tasks of managing Direct3D, Direct2D, DXGI, and the associated Win32API calls.
Keep everything inside a namespace or refactor to use a class?
WindowsApp.h
#pragma once
#include <Windows.h>
namespace WindowsApp
{
bool Initialize(HINSTANCE instanceHandle);
}
WindowsApp.cpp
#include "WindowsApp.h"
namespace WindowsApp
{
namespace
{
HWND ghMainWnd = 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
break;
default:
{
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
}
bool Initialize(HINSTANCE instanceHandle)
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = instanceHandle;
wc.hIcon = LoadIcon(0, IDI_APPLICATION);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = L"BasicWndClass";
if (!RegisterClass(&wc))
{
MessageBox(0, L"RegisterClass FAILED", 0, 0);
return false;
}
ghMainWnd = CreateWindow(
L"BasicWndClass",
L"Win32Basic",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
0,
0,
instanceHandle,
0);
if (ghMainWnd == 0)
{
MessageBox(0, L"CreateWindow FAILED", 0, 0);
}
ShowWindow(ghMainWnd, 1);
UpdateWindow(ghMainWnd);
return true;
}
}
Main.cpp
#include "WindowsApp.h"
int Run()
{
MSG msg = { 0 };
BOOL bRet = 1;
while ((bRet = GetMessage(&msg, 0, 0, 0)) != 0)
{
if (bRet == -1)
{
MessageBox(0, L"GetMessage FAILED", L"Error", MB_OK);
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// Deinitialize Here
return (int)msg.wParam;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)
{
if (!WindowsApp::Initialize(hInstance)) { return 0; }
return Run();
}
Using a namespace allows me to hide implementation details inside the nested unnamed namespace.
A class wont let me hide things but I can make them inaccessible inside the private section, that's good enough I suppose.
Using a class runs the risk of users trying to instantiate multiple objects, which, would cause the application to crash from initializing DirectX twice or something.
Namespaces avoid this issue however they present a performance degrading factor, I have to check the Initialized variable during each function call. I really dislike this.
Finally using a class requires the user to pass around the instantiated object throughout the application wherever the underlying methods are needed. That is really disappointing since the namespace approach gives me access whenever I'm inside a file that's got an #include to the namespaces header file. I really like this.
The namespace approach seems like the best way to go but something doesn't quite sit right with me in the way variables are handled inside the nested unnamed namespace. Is that an okay practice? My gut is telling me no! no! no!
So I guess my question would be: Is this an appropriate use-case for namespaces?
For Clarification:
I've got the unnamed namespace defined inside WindowsApp.cpp along with the function definitions - forward declarations to all the functions are inside WindowsApp.h - Through use of calling these functions manipulates the variables inside the unnamed namespace. Is this a bad use of namespaces or should it be done a different way? Simply including the header file in any other .cpp gives you access to the functions and in turn the underlying data. This is very appealing. My gut tells me there is some kind of performance penalty that will ensue from structuring like this.
[EDIT: Remove stuff about unnamed namespaces begin unique to TUs now the code in the question has been clarified.]
In C++ we tend to think of a class as being a wrapper for some data which maintains an invariant (as opposed to a struct, which tends to be used for a bunch of data with no invariant). The constructor establishes the invariant, the destructor tears it down, and the member functions are careful to maintain it. Here, if I've understood correctly, it seems like your invariant is that Initialized() must called prior to using any other API function.
There is another alternative, which is to use so-called "magic statics", otherwise known as "Meyers singletons". Do something like the following:
// In WindowsApp.cpp
namespace {
class WindowsAppImpl {
public:
WindowsAppImpl()
{
// Do initialization stuff here
}
~WindowsAppImpl()
{
// Do teardown stuff if necessary
}
// Example function
int getMagicNumber()
{
return 3;
}
};
WindowsAppImpl& GetInstance() {
static WindowsAppImpl instance{};
return instance;
}
} // end private namespace
// Public function declared in WindowApp.h
int GetMagicNumber() {
// Get the singleton instance
WindowsAppImpl& instance = GetInstance();
// Call member function
return instance.getMagicNumber();
}
This approach adds a function which returns a reference to the singleton WindowsAppImpl instance. The compiler guarantees that this instance is constructed exactly once, the first time GetInstance() is called. (It will also run the destructor for WindowsAppImpl after main() has finished, which is probably not important in this case but can be useful in some cases.) The advantage of this approach is that inside GetMagicNumber() you can be sure the initialization routines have been run, without requiring the user to pass around some sort of WindowsAppContext instance of their own.
I am getting errors in following code.
DWORD WINAPI CMbPoll::testThread(LPVOID lpVoid)
{
DWORD dwWaitResult;
while(1)
{
dwWaitResult = WaitForSingleObject(ghSemaphore, INFINITE/*0L*/);
if (connectionSuccessful == 1)
{
staticConnectionStatus.ShowWindow(FALSE);
}
else
{
staticConnectionStatus.ShowWindow(TRUE);
}
MessageBoxW(L"hi");
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
Read_One_t(pollSlaveId[0], pollAddress[0], 0);
temporaryCount++;
break;
case WAIT_TIMEOUT:
temporaryCount++;
break;
default:
break;
}
}
}
Errors are:
I.
at staticConnectionStatus.ShowWindow(FALSE);
error C2228: left of '.ShowWindow' must have class/struct/union
II.
at MessageBoxW(L"hi");
error C2352: 'CWnd::MessageBoxW' : illegal call of non-static member function
I am not able to understand why these errors are appearing.
My declaration for testThread is:
static DWORD WINAPI testThread(LPVOID lpVoid);
staticConnectionStatus is a member variable for static text label on a form in MFC.
DDX_Control(pDX, IDC_STATIC_CONFIG6, staticConnectionStatus);
Thank you in advance.
It's because testThread is static. A static method cannot access instance variables of a class.
The solution (this has come up a lot recently) is to make testThread non-static, and use a call back function to start the thread and call CMbPoll::testThread, using the this pointer passed to CreateThread.
DWORD WINAPI thread_starter(LPVOID lpVoid)
{
return ((CMbPoll*)lpVoid)->testThread();
}
CreateThread(..., thread_starter, this, ...);
I'm assuming that you start the thread from code in a CMbPoll method, if not then replace this with the address of your CMbPoll object.
The following code seems to be causing heap corruption whenever the debugger hits the delete[] operator. It's trying to delete a global array of structures which was defined as an extern in the header file and then declared in the global scope of the main .cpp file.
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CREATE:
{
int main_win_x, main_win_y;
tiles_horiz = 10; //temp code
tiles_vert = 10; //temp code
num_mines = 5; //temp code
main_win_x = (tiles_horiz * 22) + 20;
main_win_y = (tiles_vert * 22) + 20;
MoveWindow(hwnd, 100, 100, main_win_x, main_win_y, TRUE);
tiles_total = (tiles_horiz * tiles_vert);
tile_array = new tile[tiles_total];
SetupPlayField();
DrawInitTiles(hwnd);
}
break;
case WM_SIZE:
{
}
break;
case WM_CLOSE:
delete[] tile_array;
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
I've searched various heap corruptions topics on forums the last couple of days and so far have come up dry trying various things.
One person suggested that maybe the pointer to my array tile_array had changed by the time the program hits delete[]. But I've checked this the a couple of times and the address of both the pointer and the first element of the array remain the same.
Other forum answer from other people's posts usually suggest that I may be deleting the array more than once, but so far this is the only time the delete[] operator is used for that specific array.
Without knowing every access to the title_array it is hard to speculate on the cause of this problem. With memory corruption where the program shows up isn't always what caused it.
One thing that you may want to check is that the extern declaration is for a "tile* tile_array " and not "tile tile_array []". I very much so doubt this is the case, but when dealing with extern and arrays I have seen this mistake bite a few people.
Another thing I would do is make sure to NULL out tile_array after deleting it and when you declare it. If the problem goes away when you do this then it was in fact either a too early delete (before it was initialized) or too many deletes.
The last thing you will want to double check is that there are no buffer over/under-runs. The new[] operator places some metadata on the heap that the delete[] operator uses to know the size of the array so it can properly cleanup the memory. Corrupting this metadata can result in heap corruption.
everybody
I wanna try something and I need a little help. What I want to do is to create some functions, store their pointer into an array, then calling them inside the Windows Messages Procedure. For example:
int create_functions[10];
int paint_functions[10];
int func1() {
// code
}
void func2(int arg1) {
// code
}
create_functions[0] = *func1; // add pointer of func1 to the first array
create_functions[1] = *func2; // add pointer of func2 to the second array
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_CREATE:
// execute create_functions[0] - How do I do it?
case WM_PAINT:
// execute paint_functions[0] - How do I do it?
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
break;
}
return 0;
}
I know somebody will ask: why just don't execute the func1/func2 directly. Because I will decide what functions to be executed at run-time. Thanks to everybody for your help!
EDITED:
What about call-back functions? I don't understand very well how to use them?
If the question is: How can I do function pointers, I suggest you look at articles on the topic such as http://www.newty.de/fpt/index.html
If this is not your question, can you please edit and add more details.
This
int create_functions[10];
int paint_functions[10];
should be
void (*create_functions[10])(void);
void (*create_functions[10])(int);
and
// execute create_functions[0] - How do I do it?
// execute paint_functions[0] - How do I do it?
should be
create_functions[0]();
paint_functions[0](some_integer_here);
Also
create_functions[0] = *func1; // add pointer of func1 to the first array
create_functions[1] = *func2; // add pointer of func2 to the second array
should be
create_functions[0] = func1; // add pointer of func1 to the first array
create_functions[1] = func2; // add pointer of func2 to the second array
or
create_functions[0] = &func1; // add pointer of func1 to the first array
create_functions[1] = &func2; // add pointer of func2 to the second array
according to your taste or mood.
You can pass the pointer to your array in wParam.
Which is preferred, method 1 or method 2?
Method 1:
LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_PAINT:
{
HDC hdc;
PAINTSTRUCT ps;
RECT rc;
GetClientRect(hwnd, &rc);
hdc = BeginPaint(hwnd, &ps);
// drawing here
EndPaint(hwnd, &ps);
break;
}
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
}
return 0;
}
Method 2:
LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rc;
switch (msg)
{
case WM_PAINT:
GetClientRect(hwnd, &rc);
hdc = BeginPaint(hwnd, &ps);
// drawing here
EndPaint(hwnd, &ps);
break;
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
}
return 0;
}
In method 1, if msg = WM_PAINT when wpMainWindow function is called, does it allocate memory for all the variables on the stack at the beginning? or only when it enters the WM_PAINT scope?
Would method 1 only use the memory when the message is WM_PAINT, and method 2 would use the memory no matter what msg equaled?
Variables should be declared as locally as possible.
Declaring variables "at the top of the function" is always a disastrously bad practice. Even in C89/90 language, where variables can only be declared at the beginning of the block, it is better to declare them as locally as possible, i.e. at the beginning of smallest local block that covers the desired lifetime of the variable. Sometimes it might even make sense to introduce a "redundant" local block with the only purpose of "localizing" the variable declaration.
In C++ and C99, where it is possible to declare variable anywhere in the code, the answer is pretty straightforward: again, declare each variable as locally as possible, and as close as possible to the point where you use it the very first time. The primary rationale for that is that in most cases this will allow you to supply a meaningful initializer to the variable at the point of declaration (instead of declaring it without initializer or with a dummy initializer).
As for the memory usage, in general a typical implementation will immediately (as you enter the function) allocate the maximum space required for all variables that exist at the same time. However, your declaration habits might affect the exact size of that space. For example, in this code
void foo() {
int a, b, c;
if (...) {
}
if (...) {
}
}
all three variables exist at the same time and generally the space for all three has to be allocated. But in this code
void foo() {
int a;
if (...) {
int b;
}
if (...) {
int c;
}
}
only two variables exist at any given moment, meaning that space for only two variables will be allocated by a typical implementation (b and c will share the same space). This is another reason to declare variables as locally as possible.
Whether something's allocated on the stack in case 1 is implementation defined. Implementations aren't even required to have a stack.
It's usually no slower to do so since the operation tends to be a simple subtraction (for a downward growing stack) of one value from the stack pointer for the entire local variable area.
The thing that's important here is that the scope should be as local as possible. In other words, declare your variables as late as possible and only keep them around as long as needed.
Note that declaring here is at a different abstraction level to allocating space for them. The actual space may be allocated at the start of the function (implementation level) but you can only use those variables while they're scoped (C level).
Locality of information is important, just like its cousin, encapsulation.
I like Method 3:
LRESULT wpMainWindowPaint(HWND hwnd)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rc;
GetClientRect(hwnd, &rc);
hdc = BeginPaint(hwnd, &ps);
// drawing here
EndPaint(hwnd, &ps);
return 0;
}
LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_PAINT: return wpMainWindowPaint(hwnd);
default: return DefWindowProc(hwnd, msg, wparam, lparam);
}
}
If it deserves its own scope for organization purposes, it deserves its own function. If you're worried about function call overhead, make it inline.
Since it's the compiler's job to optimize my code, and an hour of compiler-time is way cheaper than an hour of my time, and my time gets wasted if I need to scroll up and down the code to see where a variable was declared, I think my company wants me to keep everything as local as possible.
Not even am I talking about 'the smallest block', but 'as near to the place where it is used'!
LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_PAINT:
{
RECT rc;
GetClientRect(hwnd, &rc);
{ // sometimes I even create an arbitrary block
// to show correlated statements.
// as a side-effect, the compiler may not need to allocate space for
// variables declared here...
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// drawing here
EndPaint(hwnd, &ps);
}
break;
}
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
}
return 0;
}
Define the variables in the narrowest scope where they are relevant. There's no reason to use Method 2 above in my opinion.
Stack space is only likely to be used when the variables are in scope. As #paxdiablo points out, your locals may wind up in registers rather than on the stack, if the compiler can find the space for them.
Memory allocation is not specified in the Standard to this detail, so for a real answer you'll have to specify compiler and platform. It's not going to matter for performance.
What you want is readability, and in general that's done by declaring variables in the smallest usable scope, and preferably when you can immediately initialize them with reasonable values. The smaller a variable's scope, the less it can potentially interact with the rest of the program in unpredictable ways. The closer the declaration to initialization, the less opportunity for anything bad to happen.
What would probably be better is something like
RECT rc;
GetClientRect(hwnd, &rc);
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
This is for C++. For C, the rule is similar, except that earlier versions of C required all the variables to be declared at the top of a block.
You can't know at what point the stack reservation is done.
For readability I would go with C99 (or C++). That allows you the declaration of a variable really there where first use it.
HDC hdc = BeginPaint(hwnd, &ps);
For Java programming language, the common practice is to declare local variables only when needed in a method.
void foo(int i) {
if (i == 1)
return;
Map map1 = new HashMap();
if (i == 2)
return;
Map map2 = new HashMap();
}
For C++ programming language, I also suggest the same practice since declaring variables with a non-trivial constructor involves execution cost. Putting all these declarations at the method beginning causes unneeded cost if some of these variables will be used.
void foo(int i)
{
if (i == 1)
return;
std::map<int, int> map1; // constructor is executed here
if (i == 2)
return;
std::map<int, int> map2; // constructor is executed here
}
For C, the story is different. It depends on architecture and compiler. For x86 and GCC, putting all the declarations at function beginning and declaring variables only when needed have the same performance. The reason is that C variables don't have a constructor. And the effect on stack memory allocation by these two approaches is the same. Here is an example:
void foo(int i)
{
int m[50];
int n[50];
switch (i) {
case 0:
break;
case 1:
break;
default:
break;
}
}
void bar(int i)
{
int m[50];
switch (i) {
case 0:
break;
case 1:
break;
default:
break;
}
int n[50];
}
For both functions, the assembly code for stack manipulation is:
pushl %ebp
movl %esp, %ebp
subl $400, %esp
Putting all the declarations at function beginning is common in Linux kernel code.
There's no need to pollute the stack with variables that are possibly never used. Allocate your vars right before they are used. Overlooking the RECT rc and the subsequent call to GetClientRect, Ben Voight's method is the way to go.