Skip to content

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

3 messages · Michael Bach, Simon Urbanek

#
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?

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

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