nopeva nopeva - 2 months ago 16
R Question

pass R complex object to armadillo C++

R uses, when interfacing with other languages, the header

R_ext/Complex.h
which includes the type
Rcomplex
which seems to be an implementation of
std::complex<double>
. The standard way of using it would be for a complex vector
x_
in
R
:
Rcomplex *px = COMPLEX(x_);

However, since I need to pass it to
armadillo
I then do:
arma::cx_vec x(px, nrows(x_), false, false);


but
armadillo
does not accept
Rcomplex
types. I have tried doing instead:
std::complex<double> *px = COMPLEX(x_);

but get the following
error: cannot convert ‘Rcomplex*’ to ‘std::complex<double>*’ in initialization


Do you have any clue for passing a complex vector in R to
std::complex<double> type
? I am aware of
Rcpp
but would like to have a direct solution relying on base R.

EDIT: Following one of the comments, I wanted to clarify that
Rcomplex
is of
C
type but that it is compatible with
std::complex<double>
according to the answer by @Stephen Canon.

Answer

One type can always be forced to another type using reinterpret_cast. Generally this is a bad idea, but if you can guarantee that the two complex types are indeed compatible, you can do:

 Rcomplex* px = COMPLEX(x_);
 arma::cx_vec x( reinterpret_cast<arma::cx_double*>(px), nrows(x_), false, false );

The type arma::cx_double is a shorthand for std::complex<double>