1

I'm writing a shared library with a C API, but most code is written in C++. In some places I want to throw exceptions, but I don't know what happens if third party devs would want to write a project in pure C.

What happens when a C++ shared lib throws an exception in a pure C project?

typ1232
  • 5,535
  • 6
  • 35
  • 51
Dcow
  • 1,413
  • 1
  • 19
  • 42

2 Answers2

3

Not a good idea. You'll be sure to leak memory.

A sensible alternative is for you to have a catch site within your C++ library which populates a thread specific error information object and refactor each interface function to have a return status code to signify that an error has been generated. (Cf. Microsoft's Component Object Model HRESULT and IErrorInfo). You then provide functions to call into your library to extract the error details.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

If a C++ exception bubbles up into C code then you'll get undefined behaviour. This is because the stack frames in each language for foreign to each other. The C++ runtime will attempt to unwind the stack frame into the C code and will assume that the stack frame and runtime is set up for C++ when it's actually set up for C.

If you're lucky your app will crash and you'll soon know about the problem. If you're unlucky it'll carry on for a while and you'll get some hard to find bug!

Sean
  • 60,939
  • 11
  • 97
  • 136