Confusion of global sharing variables
Recently written procedures, let the global sharing variables are harmful, will now publish the results, do not want someone to step my dust.
First summarize the experience: Global shared variable must initialize when defined, otherwise it will be invalid.
The following is written two lines of code for verification (Visual Studio .NET 2003 Windows Servers 2003):
//main.c
#include
#include "resource.h"
__Declspec (dllexport) Void Test (HWND HWND);
// Main window callback function
Lresult Callback MainProc (HWND HWND, UINT MESSAGE, WPARAM WPARAM, LPARAM LPARAM)
{
Switch (Message)
{
Case WM_COMMAND:
{
IF (loword (wparam) == iDok)
{
Test (hwnd);
Return 1;
}
Else if (loword (wparam) == iDCancel)
{
Enddialog (hwnd, 0);
Return 1;
}
}
}
Return 0;
}
Int apientry Winmain (Hinstance Hinstance, Hinstance Hprevinstance, LPSTR LPCMDLINE, INT NCMDSHOW)
{
Dialogbox (Hinstance, ID_DLG, NULL, MainProc);
Return 0;
}
///
//dll.c
#include
#include
/ / Define global shared variables
#pragma data_seg (". Shang")
Static inthainit = 0; // Initialization
Static int noinit; // Not initialized
#pragma data_seg ()
#pragma comment (Linker, "/SECTION ::shared, RWS")
__Declspec (DLLEXPORT) LRESULT CALLBACK TESTPROC (INT CODE, WPARAM WPARAM, LPARAM LPARAM)
{
IF (code> = 0)
{
CWPSTRUCT * MSG = (cwpstruct *) LPARAM;
IF (msg-> message == wm_null)
{
CHAR TEXT [50];
// payment
Haveinit = 100;
NOINIT = 100;
Sprintf (Text, "Haveinit =% D / nnoinit =% D", haveinit, noinit;
MessageBox ((hwnd) msg-> wparam, text, payment situation, MB_OK);
}
}
Return CallNexthookex (NULL, CODE, WPARAM, LPARAM);
}
__Declspec (dllexport) Void Test (HWND HWND)
{
CHAR TEXT [50];
// Look for any dialog
HWND hTEST = FINDWINDOW ("# 32770", "");
// get the thread handle of the dialog
HWND Handle = getWindowThreadProcessId (HTEST, NULL);
Handle Hlib = getModuleHandle ("DLL.DLL");
// Add hook hHOOK HOOK = SETWINDOWSHOKEX (WH_CallWndProc, TestProc, Hlib, Handle);
IF (HOOK)
{
// Send a message to activate the hook
SendMessage (HTEST, WM_NULL, (WPARAM) HWND, 0);
// Uninstall the hook
UnHookWindowshookex (HOOK);
// output result
Sprintf (Text, "Haveinit =% D / nnoinit =% D", haveinit, noinit;
MessageBox (HWND, Text, "Output", MB_OK;
}
}
/
//RES.RC
/
//
// Dialog
//
ID_DLG DIALOGEX 0, 0, 186, 90
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP |
WS_CAPTION | WS_SYSMENU
Caption "Dialog"
Font 8, "MS Shell DLG", 400, 0, 0x1
Begin
Defpushbutton "Test", IDOK, 26, 25, 50, 14
Pushbutton "Close", IDCANCEL, 99, 26, 50, 14
End
///
//Resource.h
#define id_dlg 101
Compile the above DLL.c into a DLL file, main.c is compiled into an EXE file, and the program can be explained.
The above code can be downloaded by the URL http://gg82.go.nease.net/document/g_shared.rar download.