带有指向 C 结构体的指针的 S4 对象 [英] S4 object with a pointer to a C struct

查看:49
本文介绍了带有指向 C 结构体的指针的 S4 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于编写 R 扩展的第三方 C 库.我需要创建在库中定义的一些结构(并初始化它们)我需要将它们作为 S4 对象的一部分进行维护(将这些结构视为定义计算状态,销毁它们将销毁所有剩余的计算和所有已经计算的结果).我正在考虑创建一个 S4 对象来将这些结构的指针保存为 void* 指针,但根本不清楚如何这样做,插槽的类型是什么?

I have a third-party C library I am using to write an R extension. I am required to create a few structs defined in the library (and initialize them) I need to maintain them as part of an S4 object (think of these structs as defining to state of a computation, to destroy them would be to destroy all remaining computation and the results of all that has been already computed). I am thinking of creating a S4 object to hold pointers these structs as void* pointers but it is not at all clear how to do so, what would be the type of the slot?

推荐答案

正如@hrbrmstr 所指出的,您可以使用 externalptr 类型来保持此类对象活着",这在本节 的编写 R 扩展,尽管我看不出有任何理由需要将任何内容存储为 void*.如果您使用一点 C++ 没有任何问题,Rcpp 类 XPtr 可以消除相当多的与管理 EXTPTRSXP 相关的样板文件.例如,假设以下简化示例代表您的第三方库的 API:

As pointed out by @hrbrmstr, you can use the externalptr type to keep such objects "alive", which is touched on in this section of Writing R Extensions, although I don't see any reason why you will need to store anything as void*. If you don't have any issue with using a little C++, the Rcpp class XPtr can eliminate a fair amount of the boilerplate involved with managing EXTPTRSXPs. As an example, assume the following simplified example represents your third party library's API:

#include <Rcpp.h>
#include <stdlib.h>

typedef struct {
    unsigned int count;
    double total;
} CStruct;

CStruct* init_CStruct() {
    return (CStruct*)::malloc(sizeof(CStruct));
}

void free_CStruct(CStruct* ptr) {
    ::free(ptr);
    ::printf("free_CStruct called.\n");
}

typedef Rcpp::XPtr<CStruct, Rcpp::PreserveStorage, free_CStruct> xptr_t;

当使用通过 new 创建的指针时,通常使用 Rcpp::XPtr 就足够了,因为 默认终结器 只需调用 delete 在保留目的.但是,由于您正在处理 C API,我们必须提供(默认)模板参数 Rcpp::PreserveStorage,更重要的是,提供适当的终结器(free_CStruct in这个例子),以便当相应的 R 对象被垃圾回收时,XPtr 不会在通过 malloc 等分配的内存上调用 delete.

When working with pointers created via new it is generally sufficient to use Rcpp::XPtr<SomeClass>, because the default finalizer simply calls delete on the held object. However, since you are dealing with a C API, we have to supply the (default) template parameter Rcpp::PreserveStorage, and more importantly, the appropriate finalizer (free_CStruct in this example) so that the XPtr does not call delete on memory allocated via malloc, etc., when the corresponding R object is garbage collected.

继续这个例子,假设你编写了以下函数来与你的 CStruct 交互:

Continuing with the example, assume you write the following functions to interact with your CStruct:

// [[Rcpp::export]]
xptr_t MakeCStruct() {
    CStruct* ptr = init_CStruct();
    ptr->count = 0;
    ptr->total = 0;

    return xptr_t(ptr, true);
}

// [[Rcpp::export]]
void UpdateCStruct(xptr_t ptr, SEXP x) {
    if (TYPEOF(x) == REALSXP) {
        R_xlen_t i = 0, sz = XLENGTH(x);
        for ( ; i < sz; i++) {
            if (!ISNA(REAL(x)[i])) {
                ptr->count++;
                ptr->total += REAL(x)[i];
            }
        }
        return;
    }

    if (TYPEOF(x) == INTSXP) {
        R_xlen_t i = 0, sz = XLENGTH(x);
        for ( ; i < sz; i++) {
            if (!ISNA(INTEGER(x)[i])) {
                ptr->count++;
                ptr->total += INTEGER(x)[i];
            }
        }
        return;
    }

    Rf_warning("Invalid SEXPTYPE.\n");
}

// [[Rcpp::export]]
void SummarizeCStruct(xptr_t ptr) {
    ::printf(
        "count: %d\ntotal: %f\naverage: %f\n",
        ptr->count, ptr->total,
        ptr->count > 0 ? ptr->total / ptr->count : 0
    );
}

// [[Rcpp::export]]
int GetCStructCount(xptr_t ptr) {
    return ptr->count;
}

// [[Rcpp::export]]
double GetCStructTotal(xptr_t ptr) {
    return ptr->total;
}

// [[Rcpp::export]]
void ResetCStruct(xptr_t ptr) {
    ptr->count = 0;
    ptr->total = 0.0;
}

<小时>

此时,您已经完成了足够的工作,可以开始处理 R 中的 CStructs:

  • ptr <- MakeCStruct() 将初始化一个 CStruct 并将其作为 externalptr 存储在 R
  • UpdateCStruct(ptr, x) 将修改存储在 CStruct 中的数据,SummarizeCStruct(ptr) 将打印摘要等.
  • rm(ptr);gc() 将移除 ptr 对象并强制垃圾收集器运行,从而调用 free_CStruct(ptr) 并销毁 C 端的对象还有
  • ptr <- MakeCStruct() will initialize a CStruct and store it as an externalptr in R
  • UpdateCStruct(ptr, x) will modify the data stored in the CStruct, SummarizeCStruct(ptr) will print a summary, etc.
  • rm(ptr); gc() will remove the ptr object and force the garbage collector to run, thus calling free_CStruct(ptr) and destroying the object on the C side of things as well

您提到了使用 S4 类,这是将所有这些功能包含在一个地方的一种选择.这是一种可能性:

You mentioned the use of S4 classes, which is one option for containing all of these functions in a single place. Here's one possibility:

setClass(
    "CStruct",
    slots = c(
        ptr = "externalptr",
        update = "function",
        summarize = "function",
        get_count = "function",
        get_total = "function",
        reset = "function"
    )
)

setMethod(
    "initialize",
    "CStruct",
    function(.Object) {
        .Object@ptr <- MakeCStruct()
        .Object@update <- function(x) {
            UpdateCStruct(.Object@ptr, x)
        }
        .Object@summarize <- function() {
            SummarizeCStruct(.Object@ptr)
        }
        .Object@get_count <- function() {
            GetCStructCount(.Object@ptr)
        }
        .Object@get_total <- function() {
            GetCStructTotal(.Object@ptr)
        }
        .Object@reset <- function() {
            ResetCStruct(.Object@ptr)
        }
        .Object
    }
) 

<小时>

然后,我们可以像这样使用CStruct:

ptr <- new("CStruct")
ptr@summarize()
# count: 0
# total: 0.000000
# average: 0.000000

set.seed(123)
ptr@update(rnorm(100))
ptr@summarize()
# count: 100
# total: 9.040591
# average: 0.090406

ptr@update(rnorm(100))
ptr@summarize()
# count: 200
# total: -1.714089
# average: -0.008570

ptr@reset()
ptr@summarize()
# count: 0
# total: 0.000000
# average: 0.000000

rm(ptr); gc()
# free_CStruct called.
#          used (Mb) gc trigger (Mb) max used (Mb)
# Ncells 484713 25.9     940480 50.3   601634 32.2
# Vcells 934299  7.2    1650153 12.6  1308457 10.0

<小时>

当然,另一种选择是使用 Rcpp Modules,它或多或少地处理 R 端的类定义样板(但是,使用引用类而不是 S4 类).


Of course, another option is to use Rcpp Modules, which more or less take care of the class definition boilerplate on the R side (using reference classes rather than S4 classes, however).

这篇关于带有指向 C 结构体的指针的 S4 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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