On 7 Dec 2004 08:28:33 -0800,
womanontheinside@yahoo.com wrote:
[color=blue]
> I have a library which was written in C, you call a function, it
> provides the result by a callback to specific function names. I am
> trying to wrap the calls to this inside a class, but this causes a
> problem with the callbacks, for example:
>
> class X {
> public:
> add();
> };
>
> X::add() {
> library_add(1,2);
> }
>
> library_add will return the result by calling add_result(int) callback.
> I need this function inside the class, but then it cannot be seen, and
> I get linker errors; I have to have the add_result outside of the
> class, but then it has no access to the internals of the class.[/color]
Most of the C libraries I have used that employ callbacks allow you to
register a "context" along with the function to be called. The function
then gets passed this context value as a parameter. Here's some code
snippets to show what I mean. (This code won't quite compile, as I've
mixed some declaration syntax with implementation syntax for brevity.)
void RegisterCallback (void (*function)(void *), void *context);
X::X()
{
...
// Others may comment on the advisability of doing this in the
// constructor. If you know add_result won't be called until later, I
// think it's okay.
RegisterCallback (add_result, this);
}
Now, the trick is to define two versions of add_result in your class.
One is a static member, which is the one registered. It just casts the
context pointer and calls the real function.
static void X::add_result (void *context)
{
static_cast<X*> (context)->my_add_result();
}
void X::my_add_result ()
{
...
}
If, on the other hand, your C library doesn't have any such context
notion, you may be stuck with the global pointer hack.
--
Greg Schmidt
gregs@trawna.com
Trawna Publications
http://www.trawna.com/