On Fri, 20 Aug 2004, Ross Boylan wrote:
> I am calling a C (C++ really) function via the .C interface.
> Sometimes when things go wrong I want to return an error message.
>
> 1. R provides C functions error and warning which look about right.
> But exactly how does this exit, and in particular what happens with
> cleaning up, calling C++ destructors, and unwinding the stack? Will I
> get memory leaks?
Memory handled by R will be reclaimed properly (ie R_alloc, but not
Calloc). C++ destructors will not be called -- you have to do that
yourself either before calling error() or in subsequent cleanup code that
you call from R (perhaps triggered by on.exit()).
R does have a finalizer mechanism that you could use. I have never tried
this but there are some notes at
http://www.stat.uiowa.edu/~luke/R/references/weakfinex.html
This allows C or R functions to be called by the garbage collector when an
object is disposed of. You can then put an object on the R heap so that
when R tidies this object up it will call your C++ destructors.
> 2. Before I discovered those functions, I looked at passing in a
> character vector as an argument, char ** p in the C code. Exactly how
> do I use these things? Am I supposed to allocate a string and stuff the
> pointer in the function argument? Or should I assume *p points to valid
> space (how much?) and fill it in?
If you think of p as a vector of strings (ie char *p[]) then it
corresponds to whatever strings you passed in from R. You can modify
these in place, possibly making them shorter. So if you need 80 characters
of error message, pass in a string of length at least 80.
If you want to allocate more memory you need to do this through R (either
R_alloc or the Rinternals functions). Using malloc() and stuffing the
result in, say, p[1], will cause a memory leak since you won't be able to
find it and free it.
-thomas