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" | |
*/ |
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
Yes, Simon and I exchanged on that. He is the one who came up with the preprocessor trick.