[R] the use of the .C function
Charles C. Berry
cberry at tajo.ucsd.edu
Sun Oct 14 00:22:54 CEST 2007
On Sat, 13 Oct 2007, Bernardo Lagos Alvarez wrote:
> Hi all,
>
> here others doubts, when load and running the function
>
> void gdot(double *x,double *y,int *n,double *output){
> int i;
> *output=0;
> for (i=0;i<*n;i++){
> *output+=x[i]*y[i];
> }
> }
>
>
> as following
>
> /examplesC$ R CMD SHLIB xby.c
> gcc -std=gnu99 -I/usr/share/R/include -I/usr/share/R/include -fpic -g -O2 -c xby.c
> -o xby.o
> gcc -std=gnu99 -shared -o xby.so xby.o -L/usr/lib/R/lib -lR
>
> /examplesC$ R
>> x<-c(1,4,6,2)
>> y<-c(3,2.4,1,9)
>> dyn.load("xby.so")
>> product<-.C("gdot",myx=as.double(x),myy=as.double(y),myn=as.integer(NROW(x)),myoutput=numeric())
> *** caught segfault ***
> address (nil), cause 'memory not mapped'
>
> Traceback:
> 1: .C("gdot", myx = as.double(x), myy = as.double(y), myn = as.integer(NROW(x)),
> myoutput = numeric())
>
> Possible actions:
> 1: abort (with core dump)
> 2: normal R exit
> 3: exit R without saving workspace
> 4: exit R saving workspace
> Selection:
> Selection:
> Selection:
>
>
> Can anybody answerme that happening with this Traceback?
Yes. It detects that your routine has caused a segfault.
You need to be very careful in constructing .C() calls. A _little_ mistake
there will cause loads of problems.
As section 5.2 of Writing R Extensions says
"Note that we take care to coerce all the arguments to the correct R
storage mode before calling .C; mistakes in matching the types can lead to
wrong results or hard-to-catch errors."
Also, if you get the length of one or more arguments wrong this will cause
problems.
Try to dissect your R code little by little. I suggest
you do this
product.call.args <-
list( "gdot",
myx=as.double(x),
myy=as.double(y),
myn=as.integer(NROW(x)),
myoutput=numeric() )
Can you see your mistake yet?
If not now do
print( product.call.args )
If you still cannot see your mistake look hard at 'myoutput' and the C
code.
How much storage was allocated to 'output' ??
How much does it need ??
HTH
Chuck
>
>
> Thanking you in advance,
> Bernardo Lagos A.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
More information about the R-help
mailing list