[R] Calling R from C
Ingmar Visser
I.Visser at uva.nl
Tue May 9 11:34:04 CEST 2006
Dear R-helpers,
I'm trying to transfer a loop from R code to C to improve performance using
the .Call interface. However, I ran into problems before even getting
started, and I hope (fear) I'm missing something completely obvious here.
I use the following C function (passing an integer to the C function and
printing it):
#include <R.h>
#include <Rinternals.h>
SEXP doloop(SEXP nt) {
int x=INTEGER(nt)[0];
Rprintf("x: %d \n", x);
SEXP ans;
PROTECT(ans=allocVector(REALSXP,1));
REAL(ans)[0]=0;
Rprintf("init ans: %f \n",REAL(ans)[0]);
UNPROTECT(1);
return(ans);
}
Which compiles without problems into a shared library
a1648:~ ivisser$ R CMD SHLIB -l
/Users/ivisser/Documents/projectsCurrent/dmm4Project/rfromc/
/Users/ivisser/Documents/projectsCurrent/dmm4Project/rfromc.c
gcc-4.0 -arch ppc -I/Library/Frameworks/R.framework/Resources/include
-I/Library/Frameworks/R.framework/Resources/include/ppc
-I/usr/local/include -fPIC -fno-common -g -O2 -std=gnu99 -c
/Users/ivisser/Documents/projectsCurrent/dmm4Project/rfromc.c -o
/Users/ivisser/Documents/projectsCurrent/dmm4Project/rfromc.o
gcc-4.0 -arch ppc -flat_namespace -bundle -undefined suppress
-L/usr/local/lib -o
/Users/ivisser/Documents/projectsCurrent/dmm4Project/rfromc.so
/Users/ivisser/Documents/projectsCurrent/dmm4Project/rfromc.o
-L/Library/Frameworks/R.framework/Resources/lib/ppc -lR
And then call:
>dyn.load("rfromc.so")
> .Call("doloop",nt)
With the following result (basically x is an unpredictable integer):
x: 1072693248
init ans: 0.000000
[1] 0
When I replace Rprintf("x: %d \n", x); with Rprintf("x: %f \n", x); (note
the %f) I get:
> .Call("doloop",nt)
x: 1.000000
init ans: 0.000000
[1] 0
Apparently x has the right value but is somehow represented as a double
instead of as integer
I'm using:
Version 2.3.0 (2006-04-24)
powerpc-apple-darwin8.6.0
attached base packages:
[1] "methods" "stats" "graphics" "grDevices" "utils" "datasets"
"base"
Best, Ingmar
More information about the R-help
mailing list