# Calling it from C

Firstly we need to declare to C our `result` returning C++ function:

    // Declare our C++ function's returning result type. Only needs to be done once.
    // This declares an `status_result<size_t, system_code>` which is an alias to
    // `basic_result<size_t, status_code<erased<intptr_t>>>`.
    //
    // The first parameter is some unique identifier for this type which will be used
    // whenever we reference this type in the future.
    CXX_DECLARE_RESULT_SYSTEM(to_string_rettype, size_t);

    // Tell C about our extern C++ function `to_string()`
    extern CXX_RESULT_SYSTEM(to_string_rettype) _Z9to_stringPcmi(char *buffer, size_t bufferlen, int v);

View this code on Github

Now let’s call the C++ function from C:

    void print(int v)
    {
      char buffer[4];
      CXX_RESULT_SYSTEM(to_string_rettype) res;

      res = _Z9to_stringPcmi(buffer, sizeof(buffer), v);
      if(CXX_RESULT_HAS_VALUE(res))
      {
        printf("to_string(%d) fills buffer with '%s' of %zu characters\n", v, buffer, res.value);
        return;
      }
      // Is the error returned in the POSIX domain and thus an errno?
      if(CXX_RESULT_ERROR_IS_ERRNO(res))
      {
        fprintf(stderr, "to_string(%d) failed with error code %d (%s)\n", v, (int) res.error.value, strerror((int) res.error.value));
        return;
      }
      fprintf(stderr, "to_string(%d) failed with unknown error code %lld\n", v, (long long) res.error.value);
    }

    int main(void)
    {
      print(9);
      print(99);
      print(999);
      print(9999);
      return 0;
    }

View this code on Github

Running this C program yields:

    to_string(9) fills buffer with '9' of 1 characters
    to_string(99) fills buffer with '99' of 2 characters
    to_string(999) fills buffer with '999' of 3 characters
    to_string(9999) failed with error code 105 (No buffer space available)

Last revised: February 05, 2019 at 17:14:18 UTC