Solved

Callback function and global Variable

Posted on 2003-10-28
20
725 Views
Last Modified: 2012-08-13
ok i have an app similiar to one down here....I am trying to access global variable from a call back function after modifying the variable before Callback function is invoked, why didn;t i get the updated value?

//Global variable
static int gNum = 5;

main( void )
{
  initialize();
}

void initialize()
{
  gNum = 5;
  InvokeCallback( CallbackFunc );//Calls CallbackFunc
}

static void CallbackFunc( void ** ptr)//this parameter is irrelevant to the question
{
  //Here I am trying to access gNum, I was expecting gNum to be 5, but i got 0.????
 cout<<gNum;
}
0
Comment
Question by:openujs
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 6
  • 4
  • +2
20 Comments
 
LVL 2

Expert Comment

by:MeiaDose
ID: 9636370
1st. you initialize gNum with the value of 5 and it is a global variable. So why do you do gNum=5 in your initialize function?

Apart of this question its a weird bug...

Maybe your afecting gNum somewhere else?...

0
 

Author Comment

by:openujs
ID: 9636425
oh sorry i had a typo..........
gNum is initialized as 0 at the very top.

//Global variable
static int gNum = 0;//not 5

0
 
LVL 2

Expert Comment

by:MeiaDose
ID: 9636718
I wrote this code and the value of "var" doesn´t change.

"
static int var = 0;

int CALLBACK myCallBack(){
      int i= var;
      return i;
}

void main(){
      var = 5;
      myCallBack();
}
"
I have one more question though...

Where did you found this function?
"
 InvokeCallback( CallbackFunc );//Calls CallbackFunc
"

I've searched the MSDN and i didn't found any reference to it...


0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:openujs
ID: 9636796
InvokeCallBack( CallbackFunc) is just a function i created, InvokeCallBack function invokes CallbackFunc()..I know, val of var should be 5, i keep getting 0, not sure why.
0
 
LVL 2

Expert Comment

by:MeiaDose
ID: 9636816
ok.

run the code that i've posted and tell me is the value of var is 5 inside the callback function...

Another tip:

just for debug, change "static int gNum = 5;" to "const static int gNum = 5;"

This way if anything is trying to change the value of gNum you sould notice!

Tell me is this worked please :)

Good Luck!
0
 
LVL 2

Expert Comment

by:MeiaDose
ID: 9636832
By the way, post your InvokeCallBack function please.

Thank you.
0
 

Author Comment

by:openujs
ID: 9638704
No value is still 0,  if u make gNum const static int, then i will have compiler error when i am trying to modify its value from 0 to 5. My whole point is to modfy the value and pass it to the callback function.
0
 

Author Comment

by:openujs
ID: 9638705
No value is still 0,  if u make gNum const static int, then i will have compiler error when i am trying to modify its value from 0 to 5. My whole point is to modfy the value and pass it to the callback function.
0
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9640492
Try to switch off all optimizations in the compiler options.
0
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9640533
void initialize()
{
 gNum = 5;
 CallbackFunc(NULL);
}

0 or 5 ?
0
 
LVL 9

Expert Comment

by:_ys_
ID: 9640582
The use of global variables in this way has been deprecated.

Use an unnamed namespace instead. Adherence to the C++ standard is always recommended.

//Global variable
namespace
{
    int gNum = 5;
}

If you want to modify it's value from another compilation unit provide explicit accessor functions.
0
 
LVL 5

Expert Comment

by:drnick
ID: 9642539
i think the problem could be inside invokecallback.
please post code.
0
 

Author Comment

by:openujs
ID: 9643135
Ok,,,,I am posting my actual code,  this application is actually a dll.
When another Dialog application opens, it calls the method of this dll, method called installhook( HWND handle), and passes it handle to this dll.Now inside the installhook , I am calling SetWindowsHookEx(...) this is Win API, it calls my callback method, called hookproc. I am trying to pass that HWND handle to this callback, so I declared a global HWND variable, initialized it to NULL, but inside my callback function, the handle is still NULL, even though this global HWND variable is set to be the new Window handle( handle of the dialog app window).
Here is the code........................
Also, the callback function only takes 3 params, i can not pass HWND, so i was using it as global to pass it to Callback func.

#include "stdafx.h"
#include <afxdllx.h>
#include "HookEx.h"


//Shared data among all instances
#pragma data_seg(".HOOKDATA")//Shared data among all instances.
HHOOK hook = NULL;
static HWND h = NULL;
#pragma data_seg()
#pragma comment( linker, "/SECTION:.HOOKDATA, RWS")
HINSTANCE hInst = NULL;

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

static AFX_EXTENSION_MODULE HookExDLL = { NULL, NULL };

extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
      // Remove this if you use lpReserved
      UNREFERENCED_PARAMETER(lpReserved);

      if (dwReason == DLL_PROCESS_ATTACH)
      {
            TRACE0("HOOKEX.DLL Initializing!\n");
            
            // Extension DLL one-time initialization
            if (!AfxInitExtensionModule(HookExDLL, hInstance))
                  return 0;

            // Insert this DLL into the resource chain
            // NOTE: If this Extension DLL is being implicitly linked to by
            //  an MFC Regular DLL (such as an ActiveX Control)
            //  instead of an MFC application, then you will want to
            //  remove this line from DllMain and put it in a separate
            //  function exported from this Extension DLL.  The Regular DLL
            //  that uses this Extension DLL should then explicitly call that
            //  function to initialize this Extension DLL.  Otherwise,
            //  the CDynLinkLibrary object will not be attached to the
            //  Regular DLL's resource chain, and serious problems will
            //  result.

            new CDynLinkLibrary(HookExDLL);
      }
      else if (dwReason == DLL_PROCESS_DETACH)
      {
            TRACE0("HOOKEX.DLL Terminating!\n");
            // Terminate the library before destructors are called
            AfxTermExtensionModule(HookExDLL);
      }
      hInst = hInstance;
      return 1;   // ok
}


KEYDLL3_API void  installhook( HWND handle )
{

      if( handle == NULL ) {
            MessageBox( NULL, "NULL Window Handle used", "Error!", MB_OK );
            return;
      }

      hook = NULL;
      h = handle;
      if( hInst == NULL )        MessageBox(NULL,"NULL Instance","Error!",MB_OK);
      hook = SetWindowsHookEx( WH_KEYBOARD, hookproc, hInst, NULL );
      if( hook == NULL )       MessageBox(NULL,"Unable to install hook","Error 101!",MB_OK);
      
}


KEYDLL3_API void removehook()
{
      UnhookWindowsHookEx( hook );
}

KEYDLL3_API LRESULT CALLBACK hookproc( int ncode, WPARAM wparam,LPARAM lparam)
{
      if( ncode >= 0 ){
            if( ( lparam & 0x80000000 ) == 0x00000000 ){//Only when it is pressed not released
                  
//h is NULL all the time,,,Here is the problem#########
if( h == NULL) MessageBox(NULL,"Unable to install hook","Error 102!",MB_OK);
                  BOOL bRet =      PostMessage( h, WM_USER + 755, wparam, lparam );
      
            }
      }
      return ( CallNextHookEx(hook,ncode, wparam,lparam) );//pass control to next hook in the hook chain.

}

0
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9644117
Are you sure that .HOOKDATA is really shared?
0
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9644745
I compiled the code (with some changes).
As I said before, linker does not make .HOOKDATA  as a shared segment.
I'm trying to understand why...
0
 

Author Comment

by:openujs
ID: 9644881
GlommyFrair...ok...but .HOOKDATA is really nothing to do with my problem..but u can experiment if u like to...:)
0
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9644968
>.HOOKDATA is really nothing to do with my problem
Are you sure?

Try the next code.

#pragma data_seg("myshare")//Shared data among all instances.
__declspec(allocate("myshare")) HHOOK hook;
__declspec(allocate("myshare")) HWND h;
#pragma data_seg()
#pragma comment(linker, "/SECTION:myshare,RWS")
0
 

Author Comment

by:openujs
ID: 9645087
Yes,,it works!!... u r the man!! thanks a lot:)
0
 
LVL 6

Accepted Solution

by:
GloomyFriar earned 20 total points
ID: 9648347
How about the points? ;-)
By the way I've spent a couple of hours with it, could you add some more points?
0
 

Author Comment

by:openujs
ID: 9650116
HeHe....no points for u..just a plain o thank u:)

ok i will add 10 more bonus points.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question