[Rd] Calling C functions with value parameters

Douglas Bates bates at stat.wisc.edu
Tue Aug 18 13:56:27 CEST 2009


On Mon, Aug 17, 2009 at 9:23 AM, Jeffrey J. Hallman<jhallman at frb.gov> wrote:
> One hassle I could do without is the necessity of writing C wrapper functions
> like this:
>
> void fameInit(int *status){
>  cfmini(status);
>  return;
> }
>
> when I want to call a library function (cfmini, in this case) that takes an
> int argument.  The .C interface only lets me pass a pointer to an int, rather
> than the int itself.

> Is there any chanch that .C could be enhanced to allow passing arguments by
> value to the compiled code?  It would make some of my stuff much simpler.

I suppose that if you design a new interface and submit patches to the
code in R that does the interfacing, it could be done.  However, I
imagine you would find it easier to continue to write short interface
functions like that. :-)

(By the way, the "return;" is redundant in a C function that returns void.)

You should remember that internally there are no scalar objects in R -
everything is a vector.  If you use the .Call interface, which
initially is more complicated but eventually helps you simplify your
code, arguments are passed and values returned as SEXPs and you can
use convenient utilities like asInteger which make your R code simpler
because they extract a scalar integer value from an SEXP, coercing if
necessary.

So, if you have a C function that takes two integer arguments and
returns an integer you can write the C interface function as

SEXP R_callable_foo(SEXP a, SEXP b)
{
    return ScalarInteger(foo(asInteger(a), asInteger(b)));
}


It is not surprising that you need to write interface code - it is
remarkable that it works at all.



More information about the R-devel mailing list