gpt4 book ai didi

c++ - 在 RCpp 中完成或销毁内存中的 xptr 矩阵

转载 作者:太空狗 更新时间:2023-10-29 20:41:28 27 4
gpt4 key购买 nike

这是对上一个问题 here 的跟进关于使用 xptr 在内存中存储和检索矩阵 - 这是非常好的回答 - 非常感谢。现在我可以使用 xptr 在内存中创建和检索矩阵,我该如何正确地完成/销毁对象。 Rcpp 对象应该在删除时自动进行垃圾收集,但是当我创建指针时,如果我在 R 中删除它,我必须运行 gc() 两次以恢复内存,例如

// This function wraps the matrix an returns a pointer
// [[Rcpp::export]]
SEXP writeMemObject(NumericMatrix mat)
{
XPtr<NumericMatrix> ptr(new NumericMatrix(mat), true);
return ptr;
}

检索矩阵的函数(来自之前的答案)

// [[Rcpp::export]]
NumericMatrix getMemObject(SEXP ptr)
{
XPtr<NumericMatrix> out(ptr);
return *out;
}

然后在 R 中

createMemMatrix <- function(dims){
ptr <- writeMemObject(matrix(runif(prod(dims)), nc = dims[2]))
return(ptr)
}

ptr <- createMemMatrix(c(1e4, 1e4))
#mat <- getMemObject(ptr) # this works but not run here
rm(ptr);
gc(); # nothing seems to happen in memory
gc(); # memory is freed (visible in system monitor)

bigmemory R 包在上一个问题的回答中提到,它们的对象立即释放内存

# In R
require(bigmemory)
# be careful this is a large matrix
x1 <- big.matrix(ncol = 1e4, nrow = 1e4)
x1[,] <- runif(1e8)
rm(x1)
gc() # memory is freed right away (visible on system monitor)

我尝试了在 bigmemory 包中使用的类似方法,并在创建指针时注册了它:

// C function for destroying the matrix behind the pointer
void destroyItem(SEXP ptr)
{
NumericMatrix *pm=(NumericMatrix*)(R_ExternalPtrAddr(ptr));
delete pm;
R_ClearExternalPtr(ptr);
}

// This function wraps the matrix an returns a pointer
// [[Rcpp::export]]
SEXP writeMemObject(NumericMatrix mat)
{
XPtr<NumericMatrix> ptr(new NumericMatrix(mat), true);
R_RegisterCFinalizerEx(ptr, (R_CFinalizer_t) destroyItem, (Rboolean) TRUE);
return ptr;
}

但这并没有什么不同。 bigmemory 包很棒,但我认为使用 Rcpp 对象这样做是值得的,因为内存中可以存储范围广泛的对象。

最佳答案

R 有一个分代垃圾收集器,参见示例 this section of R internals .所以调用 gc() 可能不会每次都触发完整的收集。

此外,请注意XPtr 已经注册了调用delete 的终结器,因此您无需注册destryItem 终结器。除了 delete 指针之外,您只需注册一个终结器即可执行某些操作。幸运的是,由于您的 R_ClearExternalPtr,您没有得到双重删除,但无论如何这是危险的。

关于c++ - 在 RCpp 中完成或销毁内存中的 xptr 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21205771/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com