Re: [R] Calling C code from R...wrapping C structures

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Tue, 13 May 2008 10:25:17 -0400

On 5/13/2008 7:51 AM, Nathan Harmston wrote:
> Hi everyone,
>
> I am currently trying to call some C code from R, specifically calling a
> function which populates a C struct.
>
> typedef struct{
> // contents
> } Model;
>
> void test(Model *m){
> // fill the struct with crap
> }
>
> I compile the C code into a shared library, which loads into R properly. My
> simple test functions work (i.e adding numbers etc)
> setModel <- function(){
> model<-vector("list", 6)
> name(model) <- c( SET THE NAMES OF THE MODEL HERE )
> model
> }
> t <- setModel()
> testcode <- function(setModel){
>
>
> dyn.load("Simulation.so")
>
> foo <- .C("test", Model=setModel)
> foo
> }
>
> testcode(t)
>
> However I get segfaults whenever I try to access any of the variables
> contained in Model. So my question is: am I doing something wrong here? Is
> list the right data type to wrap a structure in? I cant see any
> documentation about wrapping structs in R.
>
> Also when I pass strings to C from R they dont seem to be passed at all? Is
> this a problem with R or a problem with me and if so how do I fix it?

It is a problem in your C code. The .C interface doesn't know about the C declaration of the Model structure; it can only pass things it knows about. So your C function test() should have its header set to accept what gets passed to it. In your case, that's a list, so your C function receives an array of pointers to SEXP structures; not the easiest things to work with. Most people using .C() pass in simple vectors (numeric, integer, etc.), and use the .Call() interface if they really need R internals.

Duncan Murdoch

>
> Many Thanks in advance,
>
> Nathan
>
> [[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.



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. Received on Tue 13 May 2008 - 15:07:37 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 13 May 2008 - 15:30:38 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive