Wrapping C++ in C.

Kevin Atkinson kevinatk@home.com
Wed Feb 2 20:47:00 GMT 2000


Sorry if this is not the best place to ask, but, I could not think of a
better place.

I have 2 main questions.

1) According to the C++ Faq lite when mixing C and C++ code there are
several caveats:

* Your must use your C++ compiler when compiling main() (e.g., for
static 
  initialization) 
* Your C++ compiler should direct the linking process (e.g., so it can 
  get its special libraries) 
* Your C and C++ compilers probably need to come from same vendor 
  and have compatible versions (e.g., so they have the same calling
  conventions) 

Now, my questions are:

How much of this applies on a Posix system?
                         on a Win32 system?
                         on an ELF system?
                         on a system where the only compiler is g++?
                         on Linux?

2) Is it possible to get a function pointer out of a C++ member
function?

For example lets say I have the C struct.

struct Emulation {
  void * data // the C++ object
  const char * (* next) (void * data);
  int          (* at_end) (void * data);
  void         (* destroy) (void * data);
};

and the C++ object;

class Emulation {
  const char * next();
  int          at_end();
  ~Emulation();
};

And the C struct would be used as follows.

struct Emulation e = get_an_emulation();
while (!*e.at_end)(e.data)) {
  const char * str = (*e.next)(e.data);
  /* do something with str */
}
(*e.destroy)(e.data);

Now is it possible to set the function pointers directly equal to the
member functions to avoid the cost of an extra function call?

What if the C++ methods were virtual?

Naturally this will not be portable so I will provide backup wrapper
functions in case the compiler is not g++.

2b) What about the other way around.

If a C function implements Emulation is it even remotely possible to
directly
turn it into a C++ Emulation.  IE, manipulate the virtual table so that 
e->next() will really be calling a C function and not a C++ member
function.

I release 2b is far fetched so please don't call me crazy.

---
Kevin Atkinson
kevinatk@home.com
http://metalab.unc.edu/kevina/


More information about the Gcc mailing list