Author Topic: [C++] Simple (kinda messy) Callbacks  (Read 2885 times)

0 Members and 1 Guest are viewing this topic.

Offline rabbit

  • x86
  • Hero Member
  • *****
  • Posts: 8092
  • I speak for the entire clan (except Joe)
    • View Profile
[C++] Simple (kinda messy) Callbacks
« on: July 01, 2006, 05:51:00 pm »
I've been trying to create a callback system for a while, but with my poor C++ knowledge, it's been tricky.  I've finally created a simple, albeit messy, system for creating callback for a class, which will allow me to separate backend and output completely, yay!

Also note this was made and written on Windows XP, I'll try it on Fedora later.

main.cpp
Code: [Select]

#include "class.cpp"
#include <stdio.h>


// int _aset(int value) __attribute__ (cdecl) // GNU C++
int __cdecl _aset(int value) // Microsoft Visual Studio 6
{
printf("MyClass::a set to %d\n", value);
return 0;
}

// int _bset(char *value) __attribute__ (cdecl) // GNU C++
int __cdecl _bset(char *value) // Microsoft Visual Studio 6
{
printf("MyClass::b set to %s\n", value);
return 0;
}

int main(int argc, char **argv)
{
MyClass cls;

cls.set_aset_callback(&_aset);
cls.set_bset_callback(&_bset);

cls.set_a(42);
cls.set_b("forty two");
return 0;
}

class.cpp
Code: [Select]
class MyClass
{
protected:
int a;
char *b;

public:
void set_aset_callback(int (*callptr)(int)) { this->aset_callback_addr = callptr; };
void set_bset_callback(int (*callptr)(char *)) { this->bset_callback_addr = callptr; };

void set_a(int val)
{
this->a = val;
(*this->aset_callback_addr)(this->a);
};

void set_b(char *val)
{
this->b = val;
(*this->bset_callback_addr)(this->b);
};

private:
int (*aset_callback_addr)(int);
int (*bset_callback_addr)(char *);
};