[Rcpp-devel] What is the best practice to expose a C st ructure from 3rd party library into R?

Dirk Eddelbuettel edd at debian.org
Wed Jul 24 04:14:52 CEST 2013


Hi Wush,

After some more cleanup and consolidation, the package is now down to this:

   edd at max:~/git/rhiredis$ tree .
   .
   ├── demo
   │   ├── 00Index
   │   └── simpleRedisClient.R
   ├── DESCRIPTION
   ├── LICENSE
   ├── man
   │   └── rhiredis.Rd
   ├── NAMESPACE
   ├── R
   │   └── redis.R
   ├── README.md
   └── src
       ├── Makevars
       └── Redis.cpp
   
   4 directories, 10 files
   edd at max:~/git/rhiredis$ 

One C++ file declaring a simple class, and the Rcpp modules declaration, all
in about sixty lines -- see details at
   https://github.com/eddelbuettel/rhiredis/blob/master/src/Redis.cpp 

The R file is just one line ensuring the module gets loaded.

The demo/ script show how to use it:

   edd at max:~/git/rhiredis$ cat demo/simpleRedisClient.R 
   #!/usr/bin/Rscript

   suppressMessages(library(rhiredis))
   print(Redis)   # prints the Module's docstrings

   redis <- new(Redis)
   redis$exec("PING")		# simple PING -> PONG test
   redis$exec("PING")

   redis2 <- new(Redis, "127.0.0.1", 6379)   # create 2nd instance
   redis2$exec("SET testchannel 42")         # write some data
   redis2$exec("GET testchannel")            # retrieve

You can use any Redis command just by concatenating strings, that should also
work for serializing arbitrary R objects into (raw) strings and back.  More
user-level work could be done here.  My main focus was to provide the simple
C++ class wrapping everyhing --- without any explicit pointers, smart or
old-fashioned and not one new/delete.

The C++ file is simple too at just sixty line, see  
   

Hope this helps, and thanks for suggesting the Redis wrapper via hiredis. 

Hope this helps,  Dirk


-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com


More information about the Rcpp-devel mailing list