C++ functor as a function pointer

前端 未结 1 1925
死守一世寂寞
死守一世寂寞 2021-01-13 02:41

I have a Functor which I need to send to a function which receives a function pointer as a parameter (such as CreateThread).

Can I convert it to a stati

相关标签:
1条回答
  • 2021-01-13 03:04

    No, you can't convert a class-type object to a function pointer.

    However, you can write a non-member wrapper function that calls the member function on the right instance. Many APIs, including CreateThread, allow you to provide a pointer that it will give back to you when it calls your callback (for CreateThread, this is the lpParameter parameter). For example:

    DWORD WINAPI FunctorWrapper(LPVOID p)
    {
        // Call operator() on the functor pointed to by p:
        return (*static_cast<FunctorType*>(p))();
    }
    
    // Used as:
    FunctorType f;
    CreateThread(0, 0, &FunctorWrapper, &f, 0, 0);
    
    0 讨论(0)
提交回复
热议问题