s-news
[Top] [All Lists]

Re: passing 2d array to C function from S-plus

To: Tom Downing <td@quaestor.com>
Subject: Re: passing 2d array to C function from S-plus
From: Prof Brian Ripley <ripley@stats.ox.ac.uk>
Date: Fri, 22 Feb 2002 19:21:08 +0000 (GMT)
Cc: <s-news@lists.biostat.wustl.edu>
In-reply-to: <63EC49A6CC83D84482C9817DCF49B072029B16@paris.quaestor.com>
Arrays in S are not arrays in the C sense: they are vectors with
dimension attributes, and are double* not double**.  You definitely need
as.double(x) in the .C call, BTW, and to return something like
.C("addup", x=x, ...)$x, not the whole list.

So you need to do the multidimensional indexing yourself. There is lots of
example code out there, e.g. on statlib and in the MASS library.
S using Fortran indexing (row-major ordering).

Note that x[i][j] in C has two meanings, a 2d array and and an array of
pointers (the sense you are using).


On Fri, 22 Feb 2002, Tom Downing wrote:

> Dear All:
>
> using Visual C++ 6.0 and S+ 6
>
>
>       I am having trouble figuring out how
> to pass a 2d array to a C function, and
> receiving a 2d array in return via
> a function addup.  The function addup
> simply adds a matrix to itself (I obviously
> know this can be done in S). Anyway, the
> .dll compiles fine, and I made necessary
> changes to header file. The .dll loads
> in S, but nithing happens when I run the
> S function.    My C program is
> probably wrong and perhaps I should be
> sending this to a C list, but if anyone
> could help me out, I'd greatly appreciate
> it.  Thank you very much.
>
>
> void addup(double **x, long *n, long *k)
> {
>       long i;
>       long j;
>       long nrow = *n;
>       long ncol = *k;
>       for(i=0;i<nrow;i++){
>               for(j=0;j<ncol;j++){
>                       x[i][j] = x[i][j] * x[i][j];
>               }
>       }
> }
>
>
>
> matp <- function(x)
> {
>       .C("addup",
>               x,
>               as.integer(nrow(x)),
>               as.integer(ncol(x)))
> }
>
> is.loaded("addup")
> T
>
> x <- as.matrix(rnorm(16),4,4)
> storage.mode(x)
> "double"
> matp(x)
> #nothing happens when I run function.
> --------------------------------------------------------------------
> This message was distributed by s-news@lists.biostat.wustl.edu.  To
> unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
> the BODY of the message:  unsubscribe s-news
>

-- 
Brian D. Ripley,                  ripley@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


<Prev in Thread] Current Thread [Next in Thread>