[R] how to pass 'raw' values with cfunction()?

Dan Kelley dan.kelley at dal.ca
Sat Mar 17 20:11:28 CET 2012


I've figured this out, and am posting a solution below, in case it's of use to others. Thanks.

## test with raw
library(inline)
code <- '
unsigned char *bPtr = RAW(AS_RAW(b));
Rprintf("inside f(), b is 0X%02x\\n", *bPtr);
return(R_NilValue);'
f <- cfunction(sig=signature(b="raw"),
               body=code,
               verbose=TRUE,
               convention=".Call")
b <- as.raw(0x0f)
for (i in 1:5)
    f(b)



On 2012-03-17, at 3:02 PM, Dan Kelley wrote:

> Thanks.  .Call is better.  But how do I get the actual value of the byte (0F)?  (Updated code below.  I does not compile if I use as_RAW(*b), so I suppose that's not the method I should use.)
> 
> ## test with raw
> library(inline)
> code <- 'Rprintf("inside f(), b is 0X%x (compare %X%x)\\n", AS_RAW(b), 0x0f); return(R_NilValue);'
> f <- cfunction(sig=signature(b="raw"),
>               body=code,
>               convention=".Call")
> b <- as.raw(0x0f)
> for (i in 1:5)
>    f(b)
> 
> 
> 
> 
> On 2012-03-17, at 2:49 PM, Dirk Eddelbuettel wrote:
> 
>> 
>> On 17 March 2012 at 14:34, Dan Kelley wrote:
>> | I am having trouble handing "raw" data to a C function, using "cfunction", as demonstrated in the function and output pasted below.  Can anyone suggest what I'm doing incorrectly?  Thanks.  Dan Kelley [Dalhousie University].
>> 
>> Don't use the .C convention:
>> 
>> R> library(inline)
>> R> 
>> R> code <- 'Rprintf("inside f(), b is 0X%x\\n", *b);'
>> R> f <- cfunction(sig=signature(b="raw"),
>> +                body=code,
>> +                convention=".C")
>> R> b <- as.raw(0x0f)
>> R> for (i in 1:5)
>> +     f(b)
>> inside f(), b is 0X90
>> inside f(), b is 0X80
>> inside f(), b is 0X70
>> inside f(), b is 0X60
>> inside f(), b is 0X30
>> R> 
>> R> f2 <- cfunction(sig=signature(b="raw"), body='
>> +    Rprintf("inside f(), b is 0X%x\\n", AS_RAW(b));
>> +    return(R_NilValue);
>> + ')
>> R> b <- as.raw(0x0f)
>> R> for (i in 1:5)
>> +     f2(b)
>> inside f(), b is 0X39bf9e8
>> inside f(), b is 0X39bf9e8
>> inside f(), b is 0X39bf9e8
>> inside f(), b is 0X39bf9e8
>> inside f(), b is 0X39bf9e8
>> R> 
>> R> 
>> 
>> Dirk
>> 
>> -- 
>> "Outside of a dog, a book is a man's best friend. Inside of a dog, it is too
>> dark to read." -- Groucho Marx
>> 
> 
> 



More information about the R-help mailing list