C++包装 C 结构*和* 和函数
我正在尝试包装一个使用如下模式的 C 库:
Thing* x= new_thing_("blah");
Thing* tmp= thing_copy(x);
free_thing(tmp);
Other* y=get_other(x,7);
char* message=get_message(x,y);
free_thing(x);
free_other(y);
在 c++ 中,我希望能够执行类似的操作
auto_ptr<CXXThing> x=new CXXThing("blah");
auto_ptr<CXXThing> tmp=new CXXThing(*x);
auto_ptr<CXXOther> y=x->get_other(7);
char* message = y->get_message();
,显然,CXXOther 也包装了指向 CXXThing 的指针。所以我遇到的问题是,本质上我只想将函数和成员“插入”到现有的结构中(我认为这被称为“Mixin”想法)。
问题是,如果我包含一个 Thing 作为 CXXThing 的元素,那么我不知道如何声明构造函数,并且如果我包含一个指向包装类的指针,那么我有额外一层无用的间接。
我应该如何包装它才能实现这一点? (“你想做的不是最好的/可能的......这是正确的方法”的答案也是可以接受的。)
I'm trying to wrap a C library which uses patterns like this:
Thing* x= new_thing_("blah");
Thing* tmp= thing_copy(x);
free_thing(tmp);
Other* y=get_other(x,7);
char* message=get_message(x,y);
free_thing(x);
free_other(y);
In c++, I'd like to be able to do something like
auto_ptr<CXXThing> x=new CXXThing("blah");
auto_ptr<CXXThing> tmp=new CXXThing(*x);
auto_ptr<CXXOther> y=x->get_other(7);
char* message = y->get_message();
Obviously, CXXOther wraps a pointer to a CXXThing as well. So the problem I'm encountering is that essentially I'd like to just "insert" functions and members into existing structs (I think this is known as the "Mixin" idea).
The problem is that if I include a Thing as an element of the CXXThing, then I don't know how I'd declare the constructor, and if I include a pointer to the wrapped class, then I have an extra level of useless indirection.
How should I wrap it so that this is possible? (An answer of "What you want to do is not best/possible... here is the proper way" is also acceptable.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以更直接地使用 RAII 习惯用法,而不是使用
auto_ptr
。您可以采用以下一种方法:包装
Thing
的CXXThing
类:包装
Other
的CXXOther
类>:使用上述类将 C 代码转换为 C++ 代码:
Instead of using
auto_ptr
s, you can use the RAII idiom more directly. Here's one way you can do it:A
CXXThing
class that wraps aThing
:A
CXXOther
class that wraps anOther
:Translating your C code into C++ code with the above classes: