带有指向 C 结构的指针的 S4 对象

S4 object with a pointer to a C struct

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

正如@hrbrmstr 所指出的,您可以使用 externalptr 类型来保留此类对象 "alive",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 中提到的可以消除相当多的样板文件参与管理 EXTPTRSXPs。例如,假设以下简化示例表示您的第三方库的 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<SomeClass> 就足够了,因为 default finalizer 只是在持有的对象上调用 delete。但是,由于您正在处理 C API,我们必须提供(默认)模板参数 Rcpp::PreserveStorage,更重要的是,提供适当的终结器(本例中为 free_CStruct),以便当相应的 R 对象被垃圾回收时,XPtr 不会在通过 malloc 等分配的内存上调用 delete

继续该示例,假设您编写了以下函数来与您的 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 端销毁对象

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

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
    }
) 

然后,我们可以像这样处理 CStructs:

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 端的 class 定义样板(使用参考 classes 而不是 S4 class是的,但是)。