Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Created July 31, 2013 07:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainfrancois/6119995 to your computer and use it in GitHub Desktop.
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++.
#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"
*/
@yihui
Copy link

yihui commented Jul 31, 2013

Have you talked to Simon? He said this new feature was just a start, and he will be open to suggestions on future improvements.

@romainfrancois
Copy link
Author

Yes, Simon and I exchanged on that. He is the one who came up with the preprocessor trick.

@eibanez
Copy link

eibanez commented Feb 26, 2015

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