返回Rcpp中size_t的换行符

Return Wrap of size_t in Rcpp

本文关键字:换行符 size Rcpp 返回      更新时间:2023-10-16

我是Rcpp的新手,所以仍然盲目地四处寻找。问题的长短在于,我有一个生成指针的对象,我希望该指针返回到R。

我发现将指针投射到size_t可以保持必要的精度,但是,我似乎无法用wrap返回该精度。

在下面的代码中,只有返回的unsigned long int才会编译,其他的都会抛出错误,为了节省空间,我在这里不包括这些错误。对于我的对象,转换为unsigned long int会导致编译器由于精度丢失而失败(这是在第一个全部注释掉的块中)。

使用size_t应该足以满足我的需求,以避免为这种类型的对象创建wrap模板的替代方案。

我查看了变更日志,似乎应该支持size_t。概述还建议wrap支持size_t

#include <Rcpp.h>
#include <iostream>
using namespace Rcpp;
using namespace std;
extern "C" SEXP attempt()
{
    // this block if uncommented gives compile error that converting a pointer to unsigned long int loses precision
    // also, wrapping the pointer &f causes a compilation error
    //int f = 314;
    //unsigned long int theVar_longint = (unsigned long int) &f;
    //cout << "pointer: " << &f << endl;
    //return(wrap(&f));
    // This block makes an arbitrary value into a size_t, unsigned long int and unsigned long long int
    size_t theVar_sizet = (size_t) 383762523;
    unsigned long int theVar_longint = (unsigned long int) 383762523;
    unsigned long long int theVar_longlongint = (unsigned long long int) 383762523;
    // prints the results
    cout << "size_t: " << theVar_sizet << endl;
    cout << "longint: " << theVar_longint << endl;
    cout << "longlongint: " << theVar_longlongint << endl;
    // only the first line returns properly, the others cause errors in compilation
    return(wrap(theVar_longint));
    //return(wrap(theVar_longlongint));
    //return(wrap(theVar_sizet));
}

什么size_t、long int和long long int实际上取决于平台,所以我建议不要依赖它们,即将它们封装到R端。

我们试图通过使用int64包来支持64位整数类型,但这导致了一些问题,这些问题将得到修复。完成此操作后,您将能够包装出32位整数(int)或64位整数(int64_t)。我不建议使用size_t,long或long-long。

我有点困惑:根据定义,指针指向(瞬态?)内存位置。为什么要返回指向R的指针?

有一个定义非常明确的用例,它涉及R类型的"外部指针"(在第5.13节的编写R扩展手册中讨论)。举几个例子,ROBC等包使用R的外部指针来控制(外部)数据库连接对象,通过bigmemory与外部存储器一起工作,通过我自己的RcppDE将编译后的目标函数交给微分进化优化例程。所有这些用法对我来说都是有意义的——我们有Rcpp::XPtr类型来支持它——但仅仅传递一个指针是没有意义的。

你能更清楚地解释为什么你需要一个指针吗?

(此外,如果您试图在rcpp-devel上发帖,请确保您的From:地址与您订阅的地址完全相同。)