Calling “C++” class member function from “C” code

前端 未结 1 617
醉梦人生
醉梦人生 2020-12-03 05:04

How can we call \"C++\" class member functions in \'C\" code ?

I have two files .cpp, in which I have defined some classes with member functions and correspondin

相关标签:
1条回答
  • 2020-12-03 05:46

    C has no thiscall notion. The C calling convention doesn't allow directly calling C++ object member functions.

    Therefor, you need to supply a wrapper API around your C++ object, one that takes the this pointer explicitly, instead of implicitly.

    Example:

    // C.hpp
    // uses C++ calling convention
    class C {
    public:
       bool foo( int arg );
    };
    

    C wrapper API:

    // api.h
    // uses C calling convention
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    void* C_Create();
    void C_Destroy( void* thisC );
    bool C_foo( void* thisC, int arg );
    
    #ifdef __cplusplus
    }
    #endif
    

    Your API would be implemented in C++:

    #include "api.h"
    #include "C.hpp"
    
    void* C_Create() { return new C(); }
    void C_Destroy( void* thisC ) {
       delete static_cast<C*>(thisC);
    }
    bool C_foo( void* thisC, int arg ) {
       return static_cast<C*>(thisC)->foo( arg );
    }
    

    There is a lot of great documentation out there, too. The first one I bumped into can be found here.

    0 讨论(0)
提交回复
热议问题