简体   繁体   English

分配类回调函数到结构?

[英]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 预先感谢

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. 如果您使用的是C ++ 11或boost / function(如果没有使用),我建议您使用std :: function,它可以为您提供更多的表示能力,并且不易出错。

In general, it is not advisable to use such c-like techniques, if there is no compelling reason for doing so. 通常,如果没有令人信服的理由,建议不要使用类似c的技术。

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. 问题在于Image的成员函数(例如DrawOriginalSize )与常规函数不同-它们具有一个附加的this参数, this参数是隐式的,因此您不会“看到”该参数。 This means that a regular funciton pointer, such as img.ipp.draw can't be a member function. 这意味着常规函数指针(例如img.ipp.draw不能成为成员函数。

There are a few solutions. 有一些解决方案。 If you make draw a std::function in IMAGEPROCESSINGPARAMETER , it would work straight away. 如果在IMAGEPROCESSINGPARAMETER draw std::function ,它将立即起作用。

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. 或者,您将需要使Image的函数静态化-如果它们仍然需要成为成员函数(即,它们正在使用某些成员变量),则需要使静态包装器函数-然后包装器函数需要额外的一个参数,它是指向对象的指针,然后将其制成this指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM