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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With