• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1+++
2title = "Using Outcome from C code"
3description = "Interacting with `result` returning C++ functions from C code."
4weight = 90
5+++
6
7A long standing problem for C code (or more usually nowadays, the many other programming
8languages which can speak the C ABI but not the C++ ABI) is how to interpret C++ exception throws. The answer
9is of course that they cannot, thus requiring one to write C shim code on the C++ side
10of things of the form:
11
12```c++
13// The API we wish to expose to C
14const char *get_value(double v);
15
16// The C shim function for the C++ get_value() function.
17extern "C" int c_get_value(const char **ret, double v)
18{
19  try
20  {
21    *ret = get_value(v);
22    return 0;  // success
23  }
24  catch(const std::range_error &)
25  {
26    return ERANGE;
27  }
28  // More catch clauses may go in here ...
29  catch(...)
30  {
31    return EAGAIN;
32  }
33}
34```
35
36This is sufficiently painful that most reach for a bindings generator tool like
37[SWIG](http://www.swig.org/) to automate this sort of tedious boilerplate generation.
38And this is fine for larger projects, but for smaller projects the cost of
39setting up and configuring SWIG is also non-trivial.
40
41What would be really great is if `result<T>` returning `noexcept` C++ functions
42could be used straight from C. And indeed Experimental Outcome provides just that facility
43which this section covers next.
44