将C ++类转换为C结构(以及更高版本)

过去几天我一直在“降级”> 1000个C ++代码到C语言。直到现在一直很顺利。 突然间我和一个class级面对面……

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

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

创建自己的“构造函数”和“析构函数”作为在该结构上调用的函数

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

等等

由于C-structs不能有成员函数,你可以创建函数指针,也可以创建这些函数的非成员版本,例如:

 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方式。 请参阅此问题和最佳答案 。