[R] filling a string buffer in a C routine

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Feb 4 08:22:07 CET 2005


On Thu, 3 Feb 2005, Dan Lipsitt wrote:

> I am trying to write a C function that reads lines from a file and
> passes them back to R.

Please take a closer look at the posting guide, which clearly indicates 
this was the wrong list:

   Questions likely to prompt discussion unintelligible to non-programmers
   should go to to R-devel. For example, questions involving C, C++, etc.
   code should go to R-devel.

!!

> Here is a simplified version:
>
> --- C code ---
>
> #include <R.h>
> void read_file(char **filename, char **buf, char **buflen) {
>  FILE *infile;
>
>  infile = fopen(*filename, "r");
>  fgets(*buf, *buflen, infile);
>  fclose(infile);
> }
>
> --- R code ---
>
> buffer = "xxxxxxxxxx"            # kludge!
>
> read.file <- function(filename)
>  .C("read_climate",
>     as.character(filename),
>     buf=buffer,
>     buflen=as.integer(10))$buf
>
> --- end code ---
>
> This works okay, but the only way I could find to allocate a string
> buffer of the size I want is to use a string literal as in the line
> marked "kludge" above. It is impractical for large buffers, not to
> mention uuuggly. I tried
>
> buffer = paste(rep('x', 10), sep="")

Did you look at the result?  You need 'collapse' not 'sep'.

> but it doesn't work. So my question is, how do I do one of the following:
>
> - Allocate a character buffer of a desired size to pass to my C routine.

Use paste(collapse=)

> - Have the C routine allocate the buffer without causing a memory leak.

Use R's allocation routines discussed in `Writing R Extensions'.

> - Use .Call() instead

Lots of examples in the R sources and package sources.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list