This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: using C++ code in a C Pogram that can be compiled by gcc


Hi Ziad,

You have two choices.

1) compile/convert your C program into a C++ program. This is my recommended course of action.

2) make a C API thunk layer to your C++ library. This involves figuring out which functions you want to expose, and making a C thunk routine either in your C++ library itself, or in an ancilliary thunk C++ library, which uses 'extern "C" ...' declarations for the glue code which maps to the C++ routines. The glue routine (aka thunk routines) also have to trap any exceptions that could be thown, and repackage them into something a C program could work with.

Option #1 is probably less effort, which is why I recommend it.

For option #2, you may wonder "I have a Foo object, and I need to access it's Bar method, how do I do that?"

The thunk  routine will look something like...
extern "C" int Foo_Bar(void* vfoo, int parm1, int parm2);
int Foo_Bar(void* vfoo, int parm1, int parm2)
{
  int err = 0;
  Foo* foo = static_cast<Foo*>(vfoo);
  try
  {
    foo->Bar(parm1, parm2);
  }
  catch(...)
  {
    err = 1;
  }
  return err;
}

HTH,
--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]