On Wed, Apr 9, 2014 at 11:27 AM, Cassiano dos Santos <crn...@gmail.com> wrote:
> I am testing a call to a C function from R, using .C interface. The test
> consists in passing a numeric vector to the C function with no entries,
> dynamically allocates n positions, makes attributions and return the vector
> to R.

When execution enters your C function, the pointer x points to the
content (numerical values) of the R object known as 'x' to R code.
However, the content has length 0 and the value of the pointer may be
undefined (not sure about how R handles empty vectors).

You then change the C pointer x to point to the memory you allocated.
This memory has no relation to the R object 'x', so any changes you
make cannot be reflected in the R object x.

Further, when execution exits your function, the pointer to your
allocated memory is lost and your memory is not de-allocated (that is,
returned to the system). You should call the Free function on exit
from your function.

So the answer is that you cannot use the .C interface for this. You
could achieve your goal via the .Call interface but you have to read
up about how to work with R objects in C code.

HTH,

Peter

>
> I'm using Calloc from R.h. The prototype of the function is
>
> type* Calloc(size_t n, type)
>
> as noted in Writing R Extensions.
>
> The problem is that I don't get the new vector with the allocated positions
> in R. The vector continues to have no entries.
>
> *The code in R*
>
> fooR <- function(x) {
>   if (!is.numeric(x))
>     stop("argument x must be numeric")
>   out <- .C("foo",
>             x=as.double(x))
>   return(out$x)}
>
> x <- numeric()
>
> result <- myfooR(x)
>
> *The function in C*
>
> #include <R.h>
> void myfooRealloc(double *x){
>   int i, n;
>
>   n = 4;
>   x = Calloc(n, double);
>
>   for (i = 0; i < n; i++) {
>     x[i] = i;
>     printf("%f\n", x[i]); //just to check
>   }}
>
> The question is: Can .C inteface handle with such memory allocation?
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@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.

______________________________________________
R-help@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.

Reply via email to