返回Rcpp中size_t的换行符

时间:2012-01-19 18:12:43

标签: c++ r pointers rcpp

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

我发现将指针转换为size_t会保持必要的精度,但是,我似乎无法使用wrap返回该指针。

在下面的代码中,只返回unsigned long int将编译,其他人抛出错误,为了空间我不会在这里包含。使用我的对象,转换为unsigned long int会导致编译器因精度丢失而失败(第一个块中的所有内容都被注释掉)。

使用size_t应该足以满足我的需求,以避免为此类对象创建wrap模板。

我检查了changelog,似乎应该支持size_t。 overview还建议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));
}

2 个答案:

答案 0 :(得分:1)

size_t,long int和long long int实际上取决于平台,因此我建议不要依赖它们,即将它们包装到R端。

我们尝试使用int64包来支持64位整数类型,但这会导致一些问题,这些问题将得到解决。完成后,您将能够包装32位整数(int)或64位整数(int64_t)。我不鼓励使用size_t,长或长。

答案 1 :(得分:0)

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

的指针

有一个非常明确定义的用例,它涉及R类型的“外部指针”(在Writing R Extensions中的Section 5.13手册中讨论过)。举几个例子,R的外部指针被RODBC之类的包用来控制(外部)数据库连接对象,bigmemory用来处理外部存储器和我自己的RcppDE将编译的目标函数下放到差分进化优化程序。所有这些用法对我有意义 - 我们有Rcpp::XPtr类型来支持它 - 但只是传递一个指针不会。

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

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