Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I repass a function pointer in C++

Firstly, I am very new to function pointers and their horrible syntax so play nice.

I am writing a method to filter all pixels in my bitmap based on a function that I pass in. I have written the method to dereference it and call it in the pixel buffer but I also need a wrapper method in my bitmap class that takes the function pointer and passes it on. How do I do it? What is the syntax? I'm a little stumped.

Here is my code with all the irrelevant bits stripped out and files combined (read all variables initialized filled etc.).

struct sColour
{
    unsigned char r, g, b, a;
};

class cPixelBuffer
{
private:
    sColour* _pixels;
    int _width;
    int _height;
    int _buffersize;
public:
    void FilterAll(sColour (*FilterFunc)(sColour));
};


void cPixelBuffer::FilterAll(sColour (*FilterFunc)(sColour))
{
    // fast fast fast hacky FAST
    for (int i = 0; i < _buffersize; i++)
    {
        _pixels[i] = (*FilterFunc)(_pixels[i]);
    }
}

class cBitmap
{
private:
    cPixelBuffer* _pixels;
public:
    inline void cBitmap::Filter(sColour (*FilterFunc)(sColour))
    {
           //HERE!!
    }
};
like image 753
User2400 Avatar asked Jan 22 '23 07:01

User2400


2 Answers

If I understand what you want:

inline void cBitmap::Filter(sColour (*FilterFunc)(sColour))
{
       _pixels->FilterAll( FilterFunc);
}

Often dealing with function pointers can be made easier to read if you use a typedef for the function pointer type (yours actually isn't too bad on its own - they can get much worse very easily):

struct sColour
{
    unsigned char r, g, b, a;
};

typedef 
sColour (*FilterFunc_t)(sColour);   // typedef for a FilterFunc

class cPixelBuffer
{
private:
    sColour* _pixels;
    int _width;
    int _height;
    int _buffersize;
public:
    void FilterAll(FilterFunc_t FilterFunc);
};


void cPixelBuffer::FilterAll(FilterFunc_t FilterFunc)
{
    // fast fast fast hacky FAST
    for (int i = 0; i < _buffersize; i++)
    {
        _pixels[i] = (*FilterFunc)(_pixels[i]);
    }
}

class cBitmap
{
private:
    cPixelBuffer* _pixels;
public:
    inline void cBitmap::Filter(FilterFunc_t FilterFunc)
    {
           _pixels->FilterAll( FilterFunc);
    }
};
like image 133
Michael Burr Avatar answered Feb 04 '23 22:02

Michael Burr


The Boost libraries can make your life easier here. see boost function.
For example here is a function that takes a call back function that takes two ints and returns an int:

void do_something( boost::function<int (int, int)> callback_fn );

Then it can be used like a normal function:

int result = callback_fn(1,2);

Pass it to do_something like this:

boost::function<int (int, int)> myfn = &the_actual_fn;
do_something(myfn);

With boost function you can also pass class member functions easily (see boost bind).
Good luck with your program.

like image 40
hamishmcn Avatar answered Feb 05 '23 00:02

hamishmcn