Search code examples
c++cfmodstatic-functions

C API function callbacks into C++ member function code


So, I'm using the FMOD api and it really is a C api.

Not that that's bad or anything. Its just it doesn't interface well with C++ code.

For example, using

FMOD_Channel_SetCallback( channel, callbackFunc ) ;

It wants a C-style function for callbackFunc, but I want to pass it a member function of a class.

I ended up using the Win32 trick for this, making the member function static. It then works as a callback into FMOD.

Now I have to hack apart my code to make some of the members static, just to account for FMOD's C-ness.

I wonder if its possible in FMOD or if there's a work around to link up the callback to a specific C++ object's instance member function (not a static function). It would be much smoother.


Solution

  • You cannot directly pass a member function. A member function has the implicit parameter this and C functions don't.

    You'll need to create a trampoline (not sure the signature of the callback, so just doing something random here).

    extern "C" int fmod_callback( ... args ...)
    {
        return object->member();
    }
    

    One issue is where does that object pointer come from. Hopefully, fmod gives you a generic context value that will be provided to you when your callback is made (you can then pass in the object pointer).

    If not, you'll just need to make it a global to access it.