Is it logical to register non static method as callback function?

668 views c++
1

I created 2 class.class KeyLogger and class cHookProc

first i create cHookProc in KeyLogger class.

then i get address of LRESULT CALLBACK cHookProc::HookProc by unsigned int cHookProc::getCallBackAddr()

is it logical and works fine always?

this is KeyLogger.cpp

#include "KeyLogger.h"

KeyLogger::KeyLogger(){
    cHkProc = new cHookProc;
    int i = cHkProc->getCallBackAddr();
    HOOKPROC hprc = (HOOKPROC)i;
    HHOOK keyHook = SetWindowsHookEx(WH_KEYBOARD_LL, hprc, NULL, NULL);
}
KeyLogger::~KeyLogger(){
    delete cHkProc;
}

LRESULT CALLBACK cHookProc::HookProc(int code, WPARAM wp, LPARAM lp){
    if (code == 0){
    .
    .
    .
    }
    return CallNextHookEx(NULL, code, wp, lp);
}
void cHookProc::get_time(unsigned long miliseconds, char * const timeinfostr){
    time_t l01 = miliseconds / 1000 + starting_time;//seconds after year 1900
    tm timeinfo;
    localtime_s(&timeinfo, &l01);
    asctime_s(timeinfostr, 255, &timeinfo);//strcpy_s(timeinfostr, strlen(timeinfostr), asctime_s(timeinfo, ));
}

and this is KeyLogger.h

#pragma once
#include <time.h>
#include <windows.h>

class cHookProc{
public:
    LRESULT CALLBACK HookProc(int code, WPARAM wp, LPARAM lp);
    unsigned int getCallBackAddr();
private:
};

class KeyLogger{
public:
    KeyLogger();
    ~KeyLogger();
private:
    cHookProc *cHkProc;
};

answered question

You can't, really, since non-static member functions needs an object to be called on. If you don't have that then you could make a static member function wrapper, if that function could also access an instance (object) of the class.

Putting address into int is not going to work. Non-static member can not be registered as callback because signature mismatch.

1 Answer

13

If your function doesn't use any method from the class, then it might work, but it's just random chance, and it will break if you change the function and add references to the object. Make it a static method in that case.

A callback on a method should be wrapped with a reference to the object on which the method is called.

Also use a unique pointer for cHkProc.

posted this

Have an answer?

JD

Please login first before posting an answer.