IronAce7
IronAce7

Reputation: 35

Rcpp Enum Support

I am using Rcpp Modules to export class methods. Some of these methods have return types that are enums. For example:

#include "Enum.h"
#include <Rcpp.h>
using namespace Rcpp;

class EnumTest{
public:
  EnumTest(){}
  void setP(Polarization pol){p = pol;}
  Polarization getP(){return p;}
private:
  Polarization p;
};

RCPP_EXPOSED_CLASS(EnumTest)
RCPP_MODULE(EnumTest){
  class_<EnumTest>("EnumTest")
  .property("p", &EnumTest::getP, &EnumTest::setP)
  ;
}

Polarization is an enum, which is defined as follows:

enum Polarization{
  HORIZONTAL_POL = 0,
  VERTICAL_POL   = 1
};

When I try to build the code, I get the following error.

cannot convert 'SEXP' to 'Polarization' in initialization

Is there anyway to expose an enum to Rcpp, similar to how you can expose classes? I noticed in the Rcpp modules vignette that enum types is listed under future expansion. Does this mean there is no way to do this? If so, are there any possible workarounds?

Upvotes: 2

Views: 495

Answers (2)

Romain Francois
Romain Francois

Reputation: 17632

There is limited support for enums in Rcpp, given by the macros here.

So you can do something like this:

#include <Rcpp.h>
using namespace Rcpp; 

enum Polarization{
  HORIZONTAL_POL = 0,
  VERTICAL_POL   = 1
};

RCPP_EXPOSED_ENUM_NODECL(Polarization)

class EnumTest{
  public:
    EnumTest(){}
  void setP(Polarization pol){p = pol;}
  Polarization getP(){return p;}
  private:
    Polarization p;
};


RCPP_MODULE(Bla){
  class_<EnumTest>("EnumTest")
    .constructor()
    .property("p", &EnumTest::getP, &EnumTest::setP)
  ;
}

The support is really basic and essentially allows you to pass enums as ints, losing the class and everything. Sometimes it's enough. I'd recommend having a simple named list on the R side to make the code clearer, e.g.

Polarization <- list( HORIZONTAL_POL = 0L, VERTICAL_POL = 1L )

so that you can do e.g.

test <- new( EnumTest )
test$p <- Polarization$HORIZONTAL_POL
names(which( test$p == Polarization ))
## [1] "HORIZONTAL_POL"

Upvotes: 5

Dirk is no longer here
Dirk is no longer here

Reputation: 368181

As documented, the only interface from/to R (that we use / one should use) is

SEXP .Call(yourFunction, SEXP a, SEXP b, SEXP c, ...)

Rcpp gives your converters to/from base types. But your enum is not one of these base , so you have to write your own converters, or just pass integer values which would pass.

Upvotes: 1

Related Questions