[R] .C interface and Strings...

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Fri Jan 12 13:32:27 CET 2007



Stephane Cruveiller said the following on 1/12/2007 4:15 AM:
> Dear R users,
> 
> I am trying to include C code into R via the .C interface.  I have read
> that arguments passed to a C function have to be correctly DEreferenced.
> This is something that can be easily done for numbers (integers or 
> float) by adding
> a * before the reference like for instance:
> 
> ------------------------------------------------------------------------
> #include<R.h>
> 
> 
> void hellofct(int *n)
>    {
>        int i;
>        for (i=0;i<*n;i++)
>            {
>                Rprintf("Hello, world!\n");
>            }
>    }
> ------------------------------------------------------------------------ 
> However, I can not figure out how that can be achieved for strings.
> My prototype function would be something like:
> 
> ------------------------------------------------------------------------
> #include<R.h>
> 
> 
> void displaystring(char *str)
>    {
>        Rprintf("String displayed:%s\n", ????);
>    }
> ------------------------------------------------------------------------ 
> any hints?
> 

Yes, Section 5.2 in "Writing R Extensions".

<untested>

displaystring.c:
#include<R.h>
void displaystring(char **str, int *n)
{
   int i;
   for(i = 0; i < *n; i++)
     Rprintf("String displayed:%s\n", str[i]);
}

displaystring.dll:
R CMD SHLIB displaystring.c

displaystring.R:
dyn.load("displaystring")
displaystring <- function(x) {
   .C("displaystring", x, length(x))
   invisible()
}
displaystring(c("A", "B"))

</untested>

HTH,

--sundar



More information about the R-help mailing list