Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

class

struct

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 pointed out the error first in the header file:

class foobar {
    foo mutex;
public:
    foobar() {
        oneCreate(&mutex, NULL);
    }
    ~foobar() {
        oneDestroy(mutex);
        mutex = NULL;
    }
    void ObtainControl() {
        oneAcquire(mutex);
    }
    void ReleaseControl() {
        oneRelease(mutex);
    }
};

And of course, the C file has to take advantage of this

foobar fooey;
fooey.ObtainControl();

I don't even know where to start.... Help?

like image 678
Rasman Avatar asked May 03 '11 16:05

Rasman


People also ask

Is a struct in C the same as a class?

The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private.

Can you convert CPP to C?

It is possible to implement all of the features of ISO Standard C++ by translation to C, and except for exception handling, it typically results in object code with efficiency comparable to that of the code generated by a conventional C++ compiler.

Is struct better than class C++?

On runtime level there is no difference between structs and classes in C++ at all. So it doesn't make any performance difference whether you use struct A or class A in your code.


2 Answers

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

like image 64
ralphtheninja Avatar answered Sep 23 '22 09:09

ralphtheninja


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 );
like image 34
Dan F Avatar answered Sep 24 '22 09:09

Dan F