Passing member function pointer to the c-style function

前端 未结 3 867
慢半拍i
慢半拍i 2021-01-17 09:52

I am trying to pass member function pointer to the c-style function (as it\'s lib in C)

The pointer it wants is defined as:

void (*)(int, const char*         


        
3条回答
  •  Happy的楠姐
    2021-01-17 10:24

    Since the member function also has the this pointer as implied argument, it is not of the type accepted by the C function. Hence, IMHO the only way is to generate a standalone function with C linkage

    class A {
    public: void func(int, const char*) const;
    };
    
    extern "C" {
      void cfunc(void(*)(int, const char*));
      void call_cfunc(const A*);
    }
    
    // in some source (non-header) file:
    namespace {
      const A*pa;
      void afunc(int i, const char*s)
      { pa->func(i,s); }
    }
    
    void call_cfunc(const A*a)
    {
      pa = a;
      cfunc(afunc);
    }
    

提交回复
热议问题