Converting a C++ class to a C struct (and beyond)

前端 未结 4 710
借酒劲吻你
借酒劲吻你 2020-12-16 08:04

Past few days I have been \"downgrading\" > 1000 filem of C++ code into C. It\'s been going well until now. Suddenly I\'m face to face with a class...

The compiler

相关标签:
4条回答
  • 2020-12-16 08:32

    Turn foobar into a normal struct

    struct foobar {
        goo mutex;
    };
    

    Create your own "constructor" and "destructor" as functions that you call on that struct

    void InitFoobar(foobar* foo)
    {
       oneCreate(&foo->mutex);
    }
    
    void FreeFoobar(foobar* foo)
    {
       oneDestroy(foo->mutex);
    }
    
    struct foobar fooStruct;
    InitFoobar(&fooStruct);
    // ..
    FreeFoobar(&fooStruct);
    

    etc

    0 讨论(0)
  • 2020-12-16 08:43

    since C-structs can't have member functions, you can either make function pointers, or create non-member versions of those functions, ex:

    struct foobar {
        foo mutex;
    };
    
    Construct_foobar(foobar* fooey) {
        oneCreate(&fooey->mutex, NULL);
    }
    Destroy_foobar(foobar* fooey) {
        oneDestroy(fooey->mutex);
        fooey->mutex = NULL;
    }
    void ObtainControl(foobar* fooey) {
        oneAcquire(fooey->mutex);
    }
    void ReleaseControl(foobar* fooey) {
        oneRelease(fooey->mutex);
    }
    

    and in the .C file:

    foobar fooey;
    construct_foobar( &fooey );
    ObtainControl( &fooey );
    
    0 讨论(0)
  • 2020-12-16 08:46

    There are actually compilers that compile from C++ to C. The output is not meant for human digestion, though, see How to convert C++ Code to C.

    0 讨论(0)
  • 2020-12-16 08:58

    It depends on your compiler because there isn't a standard way of RAII in C. See this question and the top answer.

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