mercredi 8 avril 2020

Pass C++ class object in lambda capture and convert it to void pointer to pass to a C API

I am new to functional library. I want to pass lambda to a function that ultimately converts this std::function<void()> to a void pointer. I need to pass this void function to a C API. This lambda also takes in the current class object as capture. Here is the code snippet. Any help is appreciated:

class Animal{
    public:
        Animal(std::function<void()> func){}

        // call C API that takes in void(*)()
        call_c_api(func); // Somehow convert func to void *
};
class Cat{
    private:
        std::string m_name;
        Animal m_animal;
    public:
        static StaticCatFunc(Cat*instance){
               std::cout << "Name: " << instance->m_name <<"\n";
        }
        Cat(){
           m_animal = new Animal([this](){StaticCatFunc(this);})
        }
};

I need to achieve the above functionality. This is not inheritance related question. I need to somehow convert lambda with capture to a void pointer. I have read that lambdas with capture cannot be converted into raw pointers. Is there a way to achieve this functionality? Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire