[Rd] .Call interface: Use R SEXP as C mutable *char

Simon Urbanek simon.urbanek at r-project.org
Fri Mar 1 23:32:38 CET 2013


Michael,

On Mar 1, 2013, at 4:53 PM, Michael Bach wrote:

> Dear R Developers,
> 
> 
> DISCLAIMER: I am new to package development in R and new to this list.
> 
> I am trying to do something along the lines of:
> 
> SEXP test_fun (SEXP filename) {
> 
> const char *inputfile = translateChar(STRING_ELT(filename, 0));
> 
> int abc = some_function(inputfile);
> 
> ...
> 
> }
> 
> The code compiles fine, but I get a warning:
> "passing argument of 'some_function' discards qualifiers from pointer target type"
> 
> I read up on my issue and found this posting:
> https://stat.ethz.ch/pipermail/r-devel/2011-June/061221.html
> 
> I gather that the 'some_function' (which is a function from another library) takes just '*char' as argument type so the 'const' qualifier is discarded.
> 
> Of course I want my package to compile without warnings. All my other attempts led to similar 'discard' warnings (mainly initializations of helper variables).
> 
> What is the recommended approach here?
> 

Well, it really depends on some_function. The issue here is that inputfile you get is immutable (aka read-only). However, the warning tells you that some_function() declares that it wants to modify its input, so you cannot pass an immutable object to it. So there are two options (rather just one, really ;)):

a) some_function() really means it, you have to create a copy - there are many ways to do it, this is just one of them, pick your best
static char buf[512];
if (strlen(inputfile) + 1 > sizeof(buf)) Rf_error("File name is too long");
strcpy(buf, inputfile);
int abc = some_function(buf);

b) some_function() doesn't really mean it - it's just a bug in the declaration and the author really meant
int some_function(const char *fn)
This is dangerous, because you have to know for sure that this is a bug that will be fixed. Meanwhile you can work around the bug with
int abc = some_function((char*) buf);
but that will remove all checking so if some_function() decides to actually modify the argument (which it legally can as it was telling you it will), you are in deep trouble, because memory is being corrupted affecting the whole R. So don't do this!

Cheers,
Simon


> Best Regards,
> Michael Bach
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
> 
> 



More information about the R-devel mailing list