wush978
wush978

Reputation: 3174

How to expose a C structure from C library to R with Rcpp

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?

Upvotes: 4

Views: 500

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368261

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.

Upvotes: 2

Related Questions