How to use c++ objects in c?

后端 未结 3 854
清歌不尽
清歌不尽 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:46

    Give the C++ module a C interface:

    magic.hpp:

    struct Magic
    {
        Magic(char const *, int);
        double work(int, int);
    };
    

    magic.cpp: (Implement Magic.)

    magic_interface.h:

    struct Magic;
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    typedef Magic * MHandle;
    MHandle create_magic(char const *, int);
    void    free_magic(MHandle);
    double  work_magic(MHandle, int, int);
    
    #ifdef __cplusplus
    }
    #endif
    

    magic_interface.cpp:

    #include "magic_interface.h"
    #include "magic.hpp"
    
    extern "C"
    {
        MHandle create_magic(char const * s, int n) { return new Magic(s, n); }
        void    free_magic(MHandle p) { delete p; }
        double  work_magic(MHandle p, int a, int b) { return p->work(a, b); }
    }
    

    Now a C program can #include "magic_interface.h" and use the code:

    MHandle h = create_magic("Hello", 5);
    double d = work_magic(h, 17, 29);
    free_magic(h);
    

    (You might even want to define MHandle as void * and add casts everywhere so as to avoid declaring struct Magic in the C header at all.)

    0 讨论(0)
  • 2020-12-10 08:49

    Make wrapper for instantiating C++ objects using C++ exported functions.And then call these functions from C code to generate objects.

    Since one is function oriented and other is object oriented, you can use a few ideas in your wrapper:-

    1. In order to copy class member, pass an equivalent prespecified struct from C code to corresponding C++ function in order to fetch the data.
    2. Try using function pointers, as it will cut the cost, but be careful they can be exploited as well.

    A few other ways.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题