Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a string from R to C++

Tags:

c++

r

There are lots of examples of sending integers to C++ from R, but none I can find of sending strings.

What I want to do is quite simple:

SEXP convolve(SEXP filename){
  pfIn = fopen(filename, "r");
}

This gives me the following compiler error:

loadFile.cpp:50: error: cannot convert 'SEXPREC*' to 'const char*' for argument
'1' to 'FILE* fopen(const char*, const char*)'

So I need to convert filename to a const char*? Do I use CHAR?

like image 835
Chris Wheadon Avatar asked Sep 16 '10 13:09

Chris Wheadon


2 Answers

Shane shows a good trick using environments, but Chris really asked about hot to send a string down from R to C++ as a parameter. So let's answer that using Rcpp and inline:

R> fun <- cxxfunction(signature(x="character"), plugin="Rcpp", body='
+    std::string s = as<std::string>(x);
+    return wrap(s+s);  // just to return something: concatenate it
+    ')
R> fun("abc")
[1] "abcabc"
R> 

That shows the templated helper as<T> (to get stuff from R) and the complement wrap() to return back to R. If you use Rcpp, that's all that there is to it.

like image 107
Dirk Eddelbuettel Avatar answered Oct 30 '22 03:10

Dirk Eddelbuettel


Here's a method that uses R internals:

#include <R.h>
#include <Rdefines.h>

SEXP convolve(SEXP filename){
  printf("Your string is %s\n",CHAR(STRING_ELT(filename,0)));
  return(filename);

}

compile with R CMD SHLIB foo.c, then dyn.load("foo.so"), and .Call("convolve","hello world")

Note it gets the first (0th) element of the SEXP passed in and takes the string elements and CHAR converts it. Mostly taken from the Writing R Extensions guide.

Barry

like image 9
Spacedman Avatar answered Oct 30 '22 03:10

Spacedman