How to use c++ objects in c?

后端 未结 3 855
清歌不尽
清歌不尽 2020-12-10 08:07

I have 2 projects decoder and dec in my visual studio. One has C code and other has C++ code using stl respectively.How do I instantiate the c++ classes in my c code inside

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 08:50

    you would need to write a wrapper in C.

    something like this:

    in class.h:

    struct A{
       void f();
    }
    

    in class.cpp:

    void A::f(){
    }
    

    the wrapper.cpp:

    #include "wrapper.h"
    void fWrapper(struct A *a){a->f();};
    struct A *createA(){
       A *tmp=new A();
       return tmp;
    }
    
    void deleteA(struct A *a){
     delete a;
    }
    

    the wrapper.h for C:

    struct A;
    void fWrapper(struct A *a);
    A *createA();
    

    the C program:

    #include "wrapper.h"
    int main(){
        A *a;
        a=createA();
        fWrapper(a);
        deleteA(a);
    }
    

提交回复
热议问题