Date: Thu, 31 Jan 2008 15:12:32 +0100 From: "Heiko Wundram (Beenic)" <wundram@beenic.net> To: freebsd-questions@freebsd.org Subject: Re: C interpreters Message-ID: <200801311512.32396.wundram@beenic.net> In-Reply-To: <80f4f2b20801310548g33ee5f48ne90c2e86cc33346d@mail.gmail.com> References: <80f4f2b20801310548g33ee5f48ne90c2e86cc33346d@mail.gmail.com>
next in thread | previous in thread | raw e-mail | index | archive | help
Am Donnerstag, 31. Januar 2008 14:48:15 schrieb Jim Stapleton: > as a secondary (probably stupid) question: how hard is it to write a > library in C++ and allow C programs to use it? To write a library in C++ to which C programs have access, you'll have to write a set of wrapper functions for every method of a class you want to expose to C which basically get an object pointer as the first parameter and the actual method arguments as the rest. For example: test.cc ------- #include "test.hh" #include "test.h" Test::Test() { } int Test::something(int data) { return 0; } extern "C" { TestObject NewTest() { return new Test(); } int TestSomething(TestObject ob, int data) { return reinterpret_cast<Test*>(ob)->something(data); } } test.hh ------- #ifndef TEST_HH #define TEST_HH class Test { Test(); int something(int data); }; #endif // TEST_HH test.h ------ #ifndef TEST_H #define TEST_H typedef void* TestObject; #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ TestObject NewTest(); int TestSomething(TestObject ob, int data); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* TEST_H */ test.c ------ #include "test.h" int main(int argc, char** argv) { TestObject testob; testob = NewTest(); TestSomething(testob,1); } This lets you use the compiled test.cc (for example, as a library, to get around the problem of having to link your C-program against libstdc++) together with a C program. Be aware of the fact that C doesn't know function overloading, so you'll basically have to implement that by defining different methods for every type of overloaded function you want to accept. Depending on how large the C++ framework is which you're trying to wrap (and in how much it uses "advanced" C++ features), this is an easy (i.e., repetitive) or a hard/close to impossible task, especially when it comes to templates. YMMV. -- Heiko Wundram Product & Application Development
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200801311512.32396.wundram>