[R-pkg-devel] Error checking in an independent C code and printing (perror, printf, etc.)

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Tue Sep 6 18:52:55 CEST 2022


Hello Jiří and welcome to the mailing list!

On Tue, 6 Sep 2022 14:48:02 +1200
"Jiří Moravec" <jiri.c.moravec using gmail.com> wrote:

> That brings me to a problem: How to do error handling in C without
> the use of various <...> R-specific print functions?

(Assuming that's what you meant...)

One way would be to introduce callbacks from the R-independent part to
the R-interfacing part, but I can imagine this to require tedious
boilerplate. Also, many of R's entry points can raise an error
condition (e.g. if an allocation fails), which would result in a
longjmp() away from your code. Any resource not known to R's garbage
collector is going to be leaked in this situation.

I think you're actually allowed to format strings using sprintf and
friends; only actual printing to stdout/stderr is disallowed because
the user may be using e.g. Rgui on Windows and not see it at all. If
you need to print error messages, you can pass them to the R side as
strings, probably in storage allocated by the caller to avoid leaks on
errors. Error codes are of course an option too, but can be less
informative if not accompanied by an explanation of what went wrong.

(It's considered polite for package code to use R's message system not
only because of the stdout/Rgui problem mentioned above, but also
because it gives the user an option to run your code with
suppressMessages() and disable the verbose output. When the R code
directly calls cat() or the C code prints directly to console, that
option disappears.)

To summarise, R would accept any option where only R is interacting
with the user (or doing other I/O). If neither of this is satisfying,
can you provide a bit more details on the kind of error handling you're
looking for?
 
> This is my first time writing into mailing list, hopefully I am doing 
> everything ok.

Indeed you are!

-- 
Best regards,
Ivan



More information about the R-package-devel mailing list