Jon Clayden Jon Clayden - 10 months ago 34
R Question

R: Reading from an existing connection in compiled code

I'd like to be able to read from an arbitrary R connection (in the sense of

), which would be passed to an R function by the user and then down into some C code via

The R API, in file
, specifies a function,
, which takes a pointer to an
struct as its first argument, and does what I want. The struct itself is also defined in that header, but I see no way of retrieving a struct of that type, aside from
(the C function), which is not part of the API. As far as I can tell, the external pointer associated with the connection also does not point to the struct directly.

So, could anyone please tell me whether there is a supported way to convert a suitable
to a pointer to the associated

Thanks in advance.

Answer Source

The R API function R_GetConnection() was added in R 3.3.0, as documented in NEWS. It performs the conversion from SEXP to pointer to Rconn (a.k.a. Rconnection). Hence, the solution is now

#include <R_ext/Connections.h>

SEXP myfunction (SEXP conn_)
    Rconnection conn = R_GetConnection(conn_);
    // Do something with the connection

    return R_NilValue;