From ripley at stats.ox.ac.uk  Tue Jul 11 21:17:40 2006
From: ripley at stats.ox.ac.uk (Prof Brian Ripley)
Date: Tue, 11 Jul 2006 20:17:40 +0100 (BST)
Subject: [Rd] Converting SEXP to primitive C types
In-Reply-To: <45511595-A6F9-4230-A759-F5CE29612AEB@comcast.net>
References: <45511595-A6F9-4230-A759-F5CE29612AEB@comcast.net>
Message-ID: <Pine.LNX.4.64.0607112013010.15720@gannet.stats.ox.ac.uk>

On Tue, 11 Jul 2006, 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.

See `Writing R Extensions', the documentation for that file.  You cannot 
just guess that an object has the appropriate SEXPTYPE: you have to check 
it (or coerce to it).  In your example it is likely to be a REALSXP (it 
could be an INTSXP), so you need to cover all possible cases.

> 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) );
> 
> 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!


-- 
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



[Rd] Converting SEXP to primitive C types
Prof Brian Ripley