如何使用 Rcpp 将 C 结构从 C 库暴露给 R [英] How to expose a C structure from C library to R with Rcpp

查看:44
本文介绍了如何使用 Rcpp 将 C 结构从 C 库暴露给 R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 C 库中的 C 结构公开到 R 中.例如:

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

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

库提供API来构造和销毁A是很常见的:

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

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

感谢 RCPP_MODULE,不用考虑析构函数就很容易暴露它:

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
}

我喜欢这种方法,但它可能会导致内存泄漏,因为它在垃圾回收期间没有正确地破坏 A.在RCPP_MODULE中添加.finalizer(freeA)会导致free两次错误.

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.

使用 XPtr 可能是一个解决方案,但我需要手动定义函数来公开 A.flag.

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

一般来说,如何使用 Rcpp 将 C 库中的 C 结构公开到 R 中?

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

推荐答案

我建议你把你的 C 结构体变成一个 C++ 类,它允许你在构造函数中分配并在析构函数中释放.

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

您仍然可以使用不同的方式在 R 和 C++ 之间轻松地进行类转移——模块是几种可能性之一.

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

这篇关于如何使用 Rcpp 将 C 结构从 C 库暴露给 R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆