Re: [Rd] Converting SEXP to primitive C types

From: Hin-Tak Leung <>
Date: Wed 12 Jul 2006 - 13:59:53 GMT

Michael Petrovich wrote:
> I'm new to R development, so this may be a trivial question.
> In C, How do you convert a SEXP value returned by an R function to a
> primitive C type (int, double, char, array, etc.)? I've tried using
> the INTEGER(x), VECTOR_ELT(x,i), and similar functions found in /src/
> include/Rinternals.h, but doing so results in incorrect results or a
> seg-fault.
> For example, I modified /tests/Embedding/Rerror.c so that it tries to
> print the value returned by the function defined in error.R:
> val = Test_tryEval(e, &errorOccurred);
> printf("Returned: {%d}\n", VECTOR_ELT(val, 0) );

Prof Ripley had already pointed you to the "Writing R extensions" manual, which explains this stuff in more details, and also hinted that most probably it is REALSXP instead of yours guesses. So I am just going to give a somewhat concrete example - you want to be doing something like this instead:

val = Test_tryEval(e, &errorOccurred);

switch( TYPEOF(val) ) {
printf("Returned: {%f}\n", REAL(val)[0]); break;
case INTSXP:
printf("Returned: {%d}\n", INTEGER(val)[0]); break;
case STRSXP:
printf("Returned: {%s}\n", CHAR(STRING_ELT(val, 0))); break;
printf("Don't know what to do about type %d\n", TYPEOF(val)); }

> Where error.R is contains:
> foo <-
> function(x=3, y=6)
> {
> z <- x * y
> z
> }
> But the output is just "0", not the correct "18". Any ideas?
> Thanks for your help!
> ______________________________________________
> mailing list
> mailing list Received on Wed Jul 12 23:59:28 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 12 Jul 2006 - 14:31:43 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.