将c++类转换为C结构体(以及其他)



过去几天我一直在"降级"> 1000片的c++代码到C。直到现在一切都很顺利。突然间,我面对着一个班级……

编译器首先在头文件中指出错误:

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

当然,C文件必须利用这个

foobar fooey;
fooey.ObtainControl();

我甚至不知道从哪里开始....帮助吗?

将foobar转换为普通结构体

struct foobar {
    goo mutex;
};

创建自己的"构造函数"one_answers"析构函数",作为在该结构体上调用的函数

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

因为c结构体不能有成员函数,你可以创建函数指针,或者创建这些函数的非成员版本,例如:

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);
}

和。c文件中的

foobar fooey;
construct_foobar( &fooey );
ObtainControl( &fooey );

实际上有从c++编译成C的编译器。输出不是为了让人类消化,但请参阅如何将c++代码转换为C。

这取决于你的编译器,因为在c中没有标准的RAII方式。参见此问题和顶部答案

最新更新