[R] converting R objects to C types in .Call
Barry Rowlingson
B.Rowlingson at lancaster.ac.uk
Mon Jan 24 19:20:52 CET 2005
Faheem Mitha wrote:
> SEXP testfn(SEXP chstr)
> {
> char * charptr = CHAR(chstr);
> printf("%s", charptr);
> }
>
> I am sure I am making an obvious mistake, but can someone help me to
> sort it out? Thanks in advance. Please cc me, I'm not subscribed.
>
Firstly, R is expecting an SEXP as a return value! And secondly, your
SEXP chstr is still a vector - so you need to get an element from it. If
there's only one element, then that'll be the zeroth element. Here's my
code:
#include <R.h>
#include <Rinternals.h>
#include <stdio.h>
SEXP testfn(SEXP chstr)
{
char * charptr = CHAR(VECTOR_ELT(chstr,0));
printf("%s", charptr);
return(chstr);
}
- I'm just returning the same object back in the return() statement,
and using VECTOR_ELT(chstr,0) to get to the 0'th element.
SO in R:
> foo = .Call("testfn","fnord")
should print 'fnord' and return foo as "fnord".
> foo = .Call("testfn",c("bar","baz"))
will print 'bar' and return foo as c("bar","baz")
Baz
More information about the R-help
mailing list