[R] R strings from C

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Dec 19 22:15:01 CET 2001

On Wed, 19 Dec 2001, Ott Toomet wrote:

> Hi,
> I am trying to study R internal behaviour.  So long, I have not
> succeeded to access the value of R strings from C.

What you are passing is a character vector, not a string. So you need

#include <R.h>
#include <Rinternals.h>

SEXP salvesta_tabel(SEXP data_frame, SEXP file)
   printf( "nimi %s\n", CHAR(STRING_ELT(file, 0)));

to print the first element of a character vector.

Note, you have to return a SEXP, and I use %s to print a string, not %d.
I would add some testing (isString(file) && length(file) >= 1 would be a
good start).

> I use:
> void salvesta_tabel(
> 		    SEXP data_frame,
> 		    SEXP file
> 		    )
> {
>   printf( "nimi %d\n", (R_CHAR)( file));
> }
> and from the R side:
> salvesta.tabel <-
>   function (x, file = "") {
>     .Call( "salvesta_tabel", x, file)
>   }
> When calling from R as
> salvesta.tabel( x, "file")
> R always crashes while printing the %d part.  So I assume that the
> function R_CHAR is not the right one to access the value of the
> variable file, I have experimented several other ways but so long
> unsuccessfully, both Venables & Ripley ,S-programming' and ,Writing R
> extensions' seem not to touch that issue.

There *are* examples in `Writing R Extensions': search for STRING_ELT.

Fortunately there are not in `S-programming' since the way to do this has
changed since that was written.

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 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list