Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » using do_line in a class

This thread is locked; no one can reply to it. rss feed Print
using do_line in a class
HardTranceFan
Member #7,317
June 2006
avatar

I've defined a class, and within that I'm trying to use the do_line function, passing one of the methods of that class as the supplied function. However, when I try, the compiler complains with:

argument of type `void (class::)(BITMAP*, int, int, int)' does not match `void (*)(BITMAP*, int, int, int)'

Is there a way of using a class's method in do_line?

Jeroen

--
"Shame your mind don't shine like your possessions do" - Faithless (I want more part 1)

orz
Member #565
August 2000

class Bob {
public:
  virtual void draw_line_callback_in_class1(BITMAP *bmp, int x, int y) {
  }
};

void draw_line_callback_helper_1(BITMAP *bmp, int x, int y, int d) {
  Bob *bob = (Bob*)d;//only valid if sizeof(int) >= sizeof(void*)
  //if sizeof(int) is < sizeof(void*) you might try having a table of sime kind to look up which Bob you want in using d
  //if you need more parameters, instead of going for a Bob you could go for an intermediate object that contained a Bob* and something else
  ((Bob*)d)->draw_line_callback_in_class1(bmp, x, y);
}

...
do_line(screen, 0, 0, SCREEN_W-1, SCREEN_H-2, (int)bob_ptr, draw_line_callback_helper_1);

Not the best way of doing things, but it works on most 32 bit compilers. I think some people create templates to replace the helper function. Also, if you don't need a 'this' pointer, you can declare the in-class callback as static and then you can do away with the helper. See the comments for ideas on what to do on 64 bit compilers or other circumstances.

HardTranceFan
Member #7,317
June 2006
avatar

Hey Orz,

Your solution worked a treat. Thanks :)

Jeroen

--
"Shame your mind don't shine like your possessions do" - Faithless (I want more part 1)

ImLeftFooted
Member #3,935
October 2003
avatar

1// in header file
2 
3class Bob {
4public:
5 virtual void draw_line_callback_in_class1(BITMAP *bmp, int x, int y) {
6 }
7};
8 
9// ... in some source file
10static int bobPtrsIndex = 0;
11static Bob *bobPtrs[5]; // Allows max 5 threads accessing callback at once
12 
13void draw_line_callback_helper_1(BITMAP *bmp, int x, int y, int d) {
14
15 bobPtrs[d]->draw_line_callback_in_class1(bmp, x, y);
16}
17 
18// ... in some method
19int i = bobPtrsIndex++;
20bobPtrs<i> = this;
21do_line(screen, 0, 0, SCREEN_W-1, SCREEN_H-2, i, draw_line_callback_helper_1);
22--bobPtrsIndex;

Go to: