In Rcpp, how to get a user-defined structure from C into R

╄→尐↘猪︶ㄣ 提交于 2019-11-28 14:13:51

The right structure in R depends on what your struct looks like exactly. A named list is the most general one. Here a simple sample implementation for a wrap function as referred to in the comments:

#include <RcppCommon.h>

typedef struct {
  char*   firstname[128];
  char*   lastname[128];
  int      nbrOfSamples;
} HEADER_INFO;

namespace Rcpp {
  template <>
  SEXP wrap(const HEADER_INFO& x);
}

#include <Rcpp.h>

namespace Rcpp {
  template <>
  SEXP wrap(const HEADER_INFO& x) {
    Rcpp::CharacterVector firstname(x.firstname, x.firstname + x.nbrOfSamples);
    Rcpp::CharacterVector lastname(x.lastname, x.lastname + x.nbrOfSamples);
    return Rcpp::wrap(Rcpp::List::create(Rcpp::Named("firstname") = firstname,
                      Rcpp::Named("lastname") = lastname,
                      Rcpp::Named("nbrOfSamples") = Rcpp::wrap(x.nbrOfSamples)));
  };
}

//  [[Rcpp::export]]
HEADER_INFO getHeaderInfo() {
  HEADER_INFO header;
  header.firstname[0] = (char*)"Albert";
  header.lastname[0] = (char*)"Einstein";
  header.firstname[1] = (char*)"Niels";
  header.lastname[1] = (char*)"Bohr";
  header.firstname[2] = (char*)"Werner";
  header.lastname[2] = (char*)"Heisenberg";
  header.nbrOfSamples = 3;
  return header;
}

/*** R
getHeaderInfo()
 */

Output:

> getHeaderInfo()
$firstname
[1] "Albert" "Niels"   "Werner"

$lastname
[1] "Einstein"   "Bohr"       "Heisenberg"

$nbrOfSamples
[1] 3

However, for this particular case a data.frame would be more natural to use, which can be achieved by replacing above wrap with:

  template <>
  SEXP wrap(const HEADER_INFO& x) {
    Rcpp::CharacterVector firstname(x.firstname, x.firstname + x.nbrOfSamples);
    Rcpp::CharacterVector lastname(x.lastname, x.lastname + x.nbrOfSamples);
    return Rcpp::wrap(Rcpp::DataFrame::create(Rcpp::Named("firstname") = firstname,
                                              Rcpp::Named("lastname") = lastname));
  };

Output:

> getHeaderInfo()
  firstname   lastname
1    Albert   Einstein
2     Niels       Bohr
3    Werner Heisenberg
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!