[R] modifying matrix allocation functions for use with R

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Oct 6 11:41:46 CEST 2001

On Fri, 5 Oct 2001, Faheem Mitha wrote:

> Dear R people,
> I'm using compiled C code as a shared library as a backend to C code,
> using the .C interface. I need to do some matrix manipulation in the C
> code. I decided to use the new GSL (Gnu Scientific Library) currently
> (0.9.3) in beta status.
> This has appropriate matrix structures defined, and quite a comprehensive
> collection of matrix routines. However, there is a problem with the space
> allocation routines for the matrix structures, in that they use the
> standard malloc. In "Writing R Extensions" two ways are listed for doing
> memory allocation in this context, "transient memory allocation"  (5.1.1)
> and "user-controlled memory" (5.1.2). However, neither of these is the
> standard malloc, and my current understanding is because the standard
> malloc does not work with compiled libs for R.

Not so. You can use standard malloc, and people often do.
There are some BUTs though:

1) You must not mix standard malloc/free with R's Calloc/Free.  This will
crash the Windows port with great rapidity.

2) You have to check that the allocations worked and generate suitable
error handling (and terminating R via a call to exit() is not suitable).

3) You need error handlers to de-allocate the memory if your code gets

It is normally simplest to change the malloc calls, but you can also
write wrappers so that malloc calls R_alloc and free does nothing.

> My current thinking is to rewrite these routines in R. I am open to other
> suggestions. If there is anyone who has needed to use and define matrix
> routines in this context, I would be interested to hear what you did.

R has package Matrix interfacing to C++ matrix routines.

> Another option would be to define the matrices in R and pass them
> down, but this would mean having to use the .Call interface or something
> instead of the .C one, and that is a little too rich for my blood.

R matrices are quite different objects from C matrices.

> A second more general question. Is there any gain in efficiency in using
> "native" C code in place of R entry points for C code, like for random
> number generation etc?

None: the R entry points for C code are calls directly to efficient C

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 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list