[R] calling a C function with a struct

Duncan Murdoch murdoch at stats.uwo.ca
Fri Jun 6 22:04:24 CEST 2008


John Nolan wrote:
> I am trying to call a precompiled C function that uses a struct as one of
> it's arguments.
> I could write a wrapper function in C, but I was hoping there is some way
> to
> pack fields into an array of type raw that could be passed directly to the
> function.
>
> Here is some more detail.  The C struct is simple, but has mixed types:
>
>     struct STRUCT1 {
>        long type;
>        long nx;
>        double *x;
>        double a;
>        double b;
>     };
>    typedef struct STRUCT1  STRUCT1_TYPE;
>
> The C function header is
>
> void func1( long method, STRUCT1 my_struct, double *output);
>
> I would like to have an R list mimicking the C struct,
> and then use .C to call func1 with this information, e.g.
>
>    my.struct <- list(type=3,nx=5,x=1:5,a=2.5,b=8.3)
>    my.func1( 3,  convert2raw( my.struct ),   )
>   

It might be possible, but it would be quite tricky, and I'd guess the 
"double *x" would be just about impossible.  R has no way to see C level 
pointers.

Just write the wrapper in C, it will be easier than writing one in R.

Duncan Murdoch

> where R function convert2raw would return a vector of type raw with
> the fields of my.struct packed into memory just like STRUCT1, and then
> I could call func1 with that vector of raws.
>
> Can I write a convert2raw( ) function and then use
>    my.func1 <- function( method, buf ) {
>        a <- .C("func1", as.integer(method), as.raw(buf) , output=double(1)
> )
>        return(a$output)
>    }
>
>
> John
>
> ...........................................................................
>
>  John P. Nolan
>  Math/Stat Department
>  227 Gray Hall
>  American University
>  4400 Massachusetts Avenue, NW
>  Washington, DC 20016-8050
>
>  jpnolan at american.edu
>  202.885.3140 voice
>  202.885.3155 fax
>  http://academic2.american.edu/~jpnolan
>
> ...........................................................................
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
>



More information about the R-help mailing list