binding argument to ansi c callback

381 Views Asked by At

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?

2

There are 2 best solutions below

4
TheOperator On

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.

1
n. m. could be an AI On

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.