Re: How to maintain a c++ abi
On Aug 22, 9:49 am, Brendan Miller <catph...@catphive.net> wrote:
My question, is how does one engineer a library so as to provide a stable
c++ abi.
My preferred method is to reduce everything to a C abi and provide a
thin inline C++ wrapper on that.
e.g.:
// private to the library
class C
{
public:
void f();
void g();
};
// exported from the library
extern "C" {
C* create_C() { return new C; }
void destroy_C(C* c) { delete c; }
void C_f(C* c) { c->f(); }
void C_g(C* c) { c->g(); }
}
// thin wrapper for the user side
class C : boost::noncopyable
{
C* c;
public:
C() : c(create_C()) {}
~C() { destroy_C(c) }
void f() { c->f(); }
void g() { c-g(); }
};
Of course, if you want the class to be copyable you'll have to export
the equivalent of at least a copy constructor (you can probably do
without an assignment operator but you might want one as an
optimisation). Some care is required with the naming to avoid clashes
-- it's probably best to use a long prefix on the exported C
functions, the user doesn't use those names anyway. Take care only to
export the C functions from the library.
Concrete types such as std::string will need to be converted to C
equivalents when passing them; inward is generally not a problem, but
returning them can be a pain because you need to copy them then free
them -- you might need to return structure with a pointer to a release
function.
There is a certain amount of work involved, but it does help to
solidify the interface properly, and separate it from the
implementation, so it does have it's benefits.
This system also allows other languages to be used for one side or the
other -- I most recently used such a system for a library written in
Delphi with a program written in C++.
Yechezkel Mett
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]