在准备一个库(我们称之为 libfoo)时,我发现自己面临以下两难境地:我是否将其编写为带有 C 包装器的 C++ 库:
namespace Foo {
class Bar {
...
};
}
/* Separate C header. #ifdef __cplusplus omitted for brevity. */
extern "C" {
typedef void *FooBar;
FooBar* foo_bar_new() { return new Foo::Bar; }
void foo_bar_delete(FooBar *bar) { delete bar; }
}
还是将其编写为带有 C++ 包装器的 C 库更好:
/* foo/bar.h. Again, #ifdef __cplusplus stuff omitted. */
typedef struct {
/* ... */
} FooBar;
void foo_bar_init(FooBar *self) { /* ... */ }
void foo_bar_deinit(FooBar *self) { /* ... */ }
/* foo/bar.hpp */
namespace Foo {
class Bar {
/* ... */
FooBar self;
}
Bar::Bar() {
foo_bar_init(&self);
}
Bar::~Bar() {
foo_bar_deinit(&self);
}
}
你更喜欢哪个?为什么?我喜欢后者,因为这意味着我不必担心我的 C 函数会意外出现异常,而且我更喜欢 C 作为一门语言,因为我觉得它是一个较小的语义雷区。其他人怎么想?
编辑:这么多好的答案。谢谢大家。很遗憾,我只能接受一个。