4

I am trying to expose a C structure from a C library into R. For example:

struct A {
    int flag;
    // ...
}

It is common that the library provides API to construct and destroy A:

A* initA();
void freeA(A* a);

Thanks for RCPP_MODULE, It is easy to expose it without considering destructor:

#include <Rcpp.h>

using namespace Rcpp;

RCPP_EXPOSED_CLASS(A)

RCPP_MODULE(A) {
  class_<A>("A")
  .field("flag", &A::flag)
  ;
}

//'@export
//[[Rcpp::export]]
SEXP init() {
  BEGIN_RCPP
  return wrap(*initA());
  END_RCPP
}

I like this approach, but it might cause memory leak because it does not destruct A properly during garbage collection. Adding .finalizer(freeA) in RCPP_MODULE will cause an error of free twice.

Using XPtr<A, freeA> might be a solution, but I need to manually define functions to expose A.flag.

In general, how do you expose C structure from C library into R with Rcpp?

wush978
  • 3,114
  • 2
  • 19
  • 23
  • 3
    there is a mailing list for Rcpp http://lists.r-forge.r-project.org/mailman/listinfo/rcpp-devel for non-trivial questions you should ask there – statquant Jul 18 '13 at 07:15

1 Answers1

2

I suggest you turn your C struct into a C++ class which allows you allocate in the constructor and free in the destructor.

You can still use different ways to have the class transfer easily between R and C++ --- Modules is one of several possibilities.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • I agree. I tried this approach today. Care about the copy constructor because `RCPP_MODULE` calls it during constructing the object. It costed me about 30 minutes to debug. – wush978 Jul 18 '13 at 15:30
  • You do not have to use Modules. If you want more control, just write functions, say, `createInstance()` and `accessInstance()` --- but Modules can help. In any event, you will have to translate your data structure into something you can represent as a SEXP -- be iexplicitly or implicitly via Rcpp converters. – Dirk Eddelbuettel Jul 18 '13 at 15:42