I have declared a global integer variable in my program. Whenever I try to access this variable inside a keyboard...
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
hook function, I get the value of the variable as 0. But when accessed from any other function, I am getting the correct value. What could be the reason for this? I'm assuming that your keyboard hook is being loaded into another process when answering the question, which should be the case. The issue is that in Win32, global variables are not shared across processes by default. Fortunately, there's a way to mark specific sections of the Portable Executable (PE) file as shared across all address spaces.
What you'll need to do is create a new section in your DLL (dynamic link library) by specifying the name of the section using the #pragma data_seg directive like the following. For this example, I'll name the segment .RIJU, since the name can only be 8 characters long, including the initial period. You don't need the period on the front, but it's traditional.
Create and name the data segment.
#pragma data_seg (".RIJU")
Declare my global that I want shared across all processes
static int g_iSharedVariable = 0 ;
Close the data segment.
#pragma data_seg ( )
Once you've got your data segment, you'll need to tell the linker that the segment is to be marked shareable across all processes. The first way is to specify the segment as sharable in the linker definition file (.DEF). The following is a complete .DEF file that will share the .RIJU section. Note that I made up the exported function name.
; The shared data setting.
.RIJU Read Write Shared
While I prefer using the .DEF file to specify the shared section, you can also use the /SECTION LINK.EXE switch. My preference for the .DEF file is that you're guaranteed to ensure the section gets marked correctly, even if someone moves your code to a different DLL and forgets to update the build settings. If you were to use the linker, the command line switch for the above example would be the following, which you can enter in the Command Line section of the Linker property pages in Visual Studio.NET. The "rws" stands for read, write and shared.
Dig Deeper on Enterprise Infrastructure Management
Related Q&A from John Robbins
What is a JAD session? This term is referred to often in job postings and seems like some kind of brainstorm you carry out with a client to define IT...continue reading
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.