How to use c++ objects in c?

后端 未结 3 858
清歌不尽
清歌不尽 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.)

提交回复
热议问题