[R] C structures in R

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Fri Dec 1 13:37:33 CET 2006


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.

]]




More information about the R-help mailing list