Sending a string from R to C++
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?
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
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.
精彩评论