[R] Pass Vector from R to C

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Sun Jun 19 02:04:09 CEST 2011


On Sat, Jun 18, 2011 at 7:08 PM, Jaimin Dave <davejaiminm at gmail.com> wrote:
> Hi ,
> I have a function which passes a vector from R to C. However the size of the
> vector is decided inside the c program. But as I have to pass the size while
> calling the function from R lot of my space is getting wasted. Is there any
> other alternative?
>
> I call c function as :
> hi<-.C("main",v1=as.double(vector("double",1000)),v2=as.double(vector("double",1000)),v3=as.double(vector("double",1000)),v4=as.double(vector("double",1000)),"points.csv",as.integer(15000),"quad.csv")
> Here if only 250 space are filled then in remaining 750 space 0.0 is
> returned and I don't want that
> moreover I want that the resultant vector should be returned back to R.
>
> Thanks

 Either

 a) split your C into two parts, one that computes the size and
returns back to R, R then creates a vector of the right size and calls
part 2. I appreciate this might not be efficient if you have to throw
away a bunch of stuff that part 1 has done. You could pass it back to
R from part 1 and send it back to part 2.

 b) use the .Call paradigm for calling C, in which case you can create
R vectors of any size as and when you need them, and return them back
to R. Your C code will have to cooperate with the R language way of
doing things, but its all documented in the docs on this. Just be
aware things will probably crash lots until you get it right (but this
happens with .C when you get it wrong anyway)

 c) Pass a large enough vector in, get C to return the size as well as
the answers and truncate the vector down. Only works if you have some
idea of the maximum possible size (or are willing to accept a failure
on overflow) and that size isn't too large. If you are typically
talking length-1000 vectors then that's nothing. I'd not want to pass
a 100,000 length vector if you are often only sticking 10 values in
it. Although that would still be pretty quick..

Also you can make your code a bit neater by realising that:
as.double(vector("double",10)) is the same as double(10)) - I guess
you like doubles because you've put a double in your double so you can
double while you double...


Barry



More information about the R-help mailing list