user1888256
user1888256

Reputation: 167

Assign class callback function to struct?

Recently I learn about callback function and I want to implement it in my app. Here what I have got so far.

// In my image.h

typedef void (__stdcall *DrawingMethod)(IplImage*, HDC, RECT*);

typedef struct _IMAGEPROCESSINGPARAMETER {
    ...
    DrawingMethod draw;
}
IMAGEPROCESSINGPARAMETER,*PIMAGEPROCESSINGPARAMETER,*LPIMAGEPROCESSINGPARAMETER;

class Image {
    public:
        void DrawOriginalSize(IplImage*, HDC, RECT*);
        void DrawToRect(IplImage*, HDC, RECT*);
        void DrawIsotropic(IplImage*, HDC, RECT*);
        int Show();
        IMAGEPROCESSINGPARAMETER ipp;
    ...
};

// In my image.cpp

int Image::Show()
{
    // Get IplImage, HDC, and RECT and finally call the function
    ...
    DrawingMethod d = ipp.draw;
    d(img, dc, &rc);
    return 0;
}

// In main.cpp

#include "image.h"
static Image img;
...
case IDC_FILE_OPEN: {
    img.ipp.draw = img.DrawOriginalSize; // This is ERROR
    img.Show();
    break;
}

How can I make this code to works or is it wrong to write code like this?

Thank in advance

Upvotes: 0

Views: 290

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129374

You will need to do more than single simple change to "fix" this.

The problem is that the member functions of Image (such as DrawOriginalSize) are not the same as regular function - they have an additional this parameter which is implicit, so you don't "see" that parameter. This means that a regular funciton pointer, such as img.ipp.draw can't be a member function.

There are a few solutions. If you make draw a std::function in IMAGEPROCESSINGPARAMETER, it would work straight away.

Alternatively, you will need to make the functions in Image static - if they still need to be member functions (That is, they are using some member variables), you will need to make a static wrapper function - the wrapper function then takes one extra parameter, which is the pointer to the object, which is then made into a this pointer.

Upvotes: 0

Stefano Falasca
Stefano Falasca

Reputation: 9097

I would suggest you to use std::function if you are using C++11 or boost/function (if not) instead, it gives you much more representation power and is less prone to errors.

In general, it is not advisable to use such c-like techniques, if there is no compelling reason for doing so.

Upvotes: 1

Related Questions