[R] C structures in R

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Dec 1 14:21:36 CET 2006


Isn't this a question clearly in R-devel's domain?

  R-devel is intended for questions and discussion about code development
  in R. Questions likely to prompt discussion unintelligible to
  non-programmers should go to to R-devel.

The short answer is that quite a bit of code, e.g pwilcox and RODBC, does 
things like this.  You don't need to pass the pointer back to R, but if 
you do external pointers are designed for this job.  Nevertheless, 
graphics recording on Windows makes use of integers AFAIR to store C-level 
structures (but it predates raw and external pointers).

On Fri, 1 Dec 2006, Barry Rowlingson wrote:

> Is it safe to call C code from R that mallocs memory for a structure,
> returning a pointer to that structure via some 'raw()' parameter. Then,
> pass that pointer to another C routine, and finally free the malloced
> memory by passing the raw() data to another C routine?
>
> I've written some code that does this, I'm just not sure if anything
> could go wrong. The worst I can come up with is a memory leak if the
> structure's memory isn't freed - possibly because the R is interrupted.
>
> R isn't going to stomp on memory that's been malloced by an included C
> routine between .C calls though, is it?
>
> Barry
>
> [[
> gory details:
>
>   R code calls a C routine with .C passing a 4-byte (because 4 is
> sizeof(char*) in my architecture) 'raw' object, the C code then mallocs
> the structure and copies the address of the structure into the 4 bytes
> that the raw object (which appears as a char* in the C routine argument
> list) points to. This gets returned back to R. Another option would be
> to create a raw object of the right size to store my structure, pass
> that to C and not malloc anything in C. But that would mean altering the
> C code which I want to do as little as possible.
>
> gory code available on request.
>
> ]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>

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




More information about the R-help mailing list