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

Michael Bach phaebz at gmail.com
Sat Mar 2 19:37:10 CET 2013


On 3/1/13 11:32 PM, Simon Urbanek wrote:
>> 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!
>

I took The Only True Option b), i.e. a manual 'fix' and modified the .c 
and .h argument lists to 'const char *fn' after confirming that 
some_function() does indeed not change the argument. I also filed a bug 
and submitted a patch upstream.

Thanks Simon for clarifications!

Best Regards,
Michael



More information about the R-devel mailing list