C interpreters
Heiko Wundram (Beenic)
wundram at beenic.net
Thu Jan 31 06:11:18 PST 2008
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
More information about the freebsd-questions
mailing list