0

I have function, lets say foo, in lib which accepts callback:

typedef void (*CallbackType)(unsigned int); 
void foo(const tchar* path, CallBackType); // library function

static void boo(unsigned int percent)
{
static ProgressBarClass progressBar;
 progressBar.setProgressValue(percent);
}

but I can't have object progressBar to be static, so I thought I will bind reference to it:

static void boo(unsigned int percent, ProgressBarClass& progressBar)
{
    progressBar.setProgressValue(percent);
}

void something() {
    ProgressBarClass progressBar;
    tr1::function<static void(unsigned int)> f = tr1::bind(boo, tr1::placeholders::_1, tr1::ref(progressBar));
    foo(someWCHARPath, f);
}

but of course I can't convert tr1::function to ansi c callback, so the question is is there anything nice and clean what can I do? Can I bind progressBar is some way to ansi c callback?

Lundin
  • 195,001
  • 40
  • 254
  • 396

2 Answers2

1

You have to resort to a global function with exactly that signature. Since you're given the function pointer type typedef void (*CallbackType)(unsigned int), your callback needs to return void and take one unsigned int parameter:

void function(unsigned int);
CallbackType funcPtr = &function;

If the callback doesn't provide a "user data" argument (usually a void*) to pass additional data, you either have to fit them somehow to the existing arguments (maybe it's possible to use some bits of the integer), or use global variables, which I wouldn't recommend unless absolutely necessary.

TheOperator
  • 5,936
  • 29
  • 42
  • can you give me some example how you imagine that "resort to a global function"? – DeSubstantiisSeparatis Oct 14 '15 at 07:11
  • @user1326505 I edited my answer correspondingly. Basically, in C you don't have an option to use any of the nice features (e.g. bind, lambda) that C++11 functionals provide. – TheOperator Oct 14 '15 at 07:16
  • well boo function is that global one, but it has to get same reference to ProgressBarClass object class somehow, so I can use boo function for example 100 times. maybe there is just no good solution... – DeSubstantiisSeparatis Oct 14 '15 at 07:31
  • Yes, I'm afraid there is no clean solution in that case (only global variables, which allow only a single callback to be executed simultaneously and introduce many other problems). That's why well-thought C callback APIs provide additional `void*` arguments. – TheOperator Oct 14 '15 at 07:40
0

If any object of type ProgressBarClass is OK, just remove the static keyword.

If you need some specific object of type ProgressBarClass, then no, there's no way to pass one around through the C callback you have. You must have some kind of static variable which allows you to get the object. It doesn't have to be a ProgressBarClass. Perhaps you should have a singleton that represent your application, with methods that return its various GUI elements.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243