且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将成员函数作为参数传递? (PortAudio)

更新时间:2023-11-09 23:21:46

有两种方法可以做到这一点.您可以使用void* userData参数从非成员(或静态)函数指向您的类,并从该函数访问您的类.或者,您可以使用该非成员(或静态)函数在对象上调用成员函数:

There are a couple of ways you can do this. You can use the void* userData parameter to point to your class from a non member (or static) function and access your class from that function. Or you can use that non member (or static) function to call a member function on your object:

class MyClass
{
public:

    void register_callback_here()
    {
        Pa_OpenDefaultStream(stream, 2, 2, PaSampleFormat::whatever, 44100,
            1024, &MyClass::pa_callback_mapper, this); // PASS this!!!
    }

private:

    // The actual call back
    int callback(
        const void* input, void* output,
        unsigned long frameCount,
        const PaStreamCallbackTimeInfo* timeInfo,
        PaStreamCallbackFlags statusFlags)
    {
        // actual callback here
        return 0;
    }

    // a pass-through function that reinterprets the userData as the this pointer
    // then cals the member function using this.
    static int pa_callback_mapper(
        const void* input, void* output,
        unsigned long frameCount,
        const PaStreamCallbackTimeInfo* timeInfo,
        PaStreamCallbackFlags statusFlags,
        void* userData)
    {
        if(auto self = reinterpret_cast<MyClass*>(userData))
            return self->callback(input, output, frameCount, timeInfo, statusFlags);
        return 0;
    }
};

注册回叫时,您将this作为userData传递.回调在回调函数中将指针返回给您.您可以将其强制转换为您的类类型,然后通过它访问您的类,或将调用转发给成员函数(如本例所示).

When you register the call back you pass this as the userData. The callback gives that pointer back to you in your callback function. You can cast it back to your class type and either access your class through it or forward the call to a member function (as in this example).