Created
July 31, 2013 07:20
-
-
Save romainfrancois/6119995 to your computer and use it in GitHub Desktop.
Two workarounds to get access to the c level connections api from c++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Rcpp.h> | |
// thanks to Simon for the macro magic | |
// problem #1: R internals uses "private" and "class" as | |
// member names. So a C++ compiler is confused | |
// when we include Connections.h | |
// this workaround uses the preprocessor to rename | |
// class as class_name and private as private_ptr | |
#define class class_name | |
#define private private_ptr | |
#include <R_ext/Connections.h> | |
#undef class | |
#undef private | |
// problem #2: getConnection is not part of the R exported API | |
// but it is not hidden, so we can cheat and get it | |
// like this. Not sure crandalf won't "you shall not pass" | |
// that kind of workaround | |
extern "C" { | |
extern Rconnection getConnection(int) ; | |
} | |
using namespace Rcpp ; | |
// [[Rcpp::export]] | |
std::string foo(SEXP con_){ | |
Rconnection con = getConnection( as<int>(con_) ) ; | |
return con->class_name ; | |
} | |
/*** R | |
con <- textConnection( "foobar" ) | |
f <- file( "con.cpp" ); | |
foo( con ) | |
# [1] "textConnection" | |
foo( f ) | |
# [1] "file" | |
*/ |
Probably not. I'd rather work on some c++ abstractions around it and gallery that.
I'm planning to add some connections api in Rcpp, but probably not for the next (september) release. Lots of other stuff in the pipes already.
Have you talked to Simon? He said this new feature was just a start, and he will be open to suggestions on future improvements.
Yes, Simon and I exchanged on that. He is the one who came up with the preprocessor trick.
I was wondering if you had done more work in this direction. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works like a charm. Thanks for doing that and more generally for Rcpp.
I think it will open a lot of possibilities for R users.
Will you post it to the gallery ? it will very be nice to have it there.