Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

Rcpp: how to use unwind protection?

I was wondering how could I make some Rcpp code use automatic unwind protection in all Rcpp object creations.

For example, suppose I have some code like this:

#include <stdint.h>
#include <Rcpp.h>

class MyObj {
public:
    int val;
    MyObj(int val) : val(val) {};
    ~MyObj() {
        std::cout << "I' being destructed - value was: " << val << std::endl;
    }
};

// [[Rcpp::export]]
Rcpp::NumericVector crashme(unsigned int seed)
{
    srand(seed);
    MyObj obj1(rand());
    Rcpp::NumericVector out(INT64_MAX-1, 100.);
    return out;
}

When I call crashme, obj1 doesn't get destructed before the function ends, due to R's long jumps which I want to protect against.

I see there is a function Rcpp::unwindProtect, but it's implemented as something that takes a callback.

I'm not 100% sure if I'm doing it right, but I managed to add unwind protection like this:

#include <stdint.h>
#include <Rcpp.h>
#include <Rcpp/unwindProtect.h>
// [[Rcpp::plugins(unwindProtect)]]

class MyObj {
public:
    int val;
    MyObj(int val) : val(val) {};
    ~MyObj() {
        std::cout << "I' being destructed - value was: " << val << std::endl;
    }
};

struct NumVecArgs {
    size_t size;
    double fillwith;
};

SEXP alloc_NumVec(void *data)
{
    NumVecArgs *args = (NumVecArgs*)data;
    return Rcpp::NumericVector(args->size, args->fillwith);
}

// [[Rcpp::export]]
Rcpp::NumericVector crashme(unsigned int seed)
{
    srand(seed);
    MyObj obj1(rand());
    NumVecArgs args = {INT64_MAX-1, 100.};
    Rcpp::NumericVector out = Rcpp::unwindProtect(alloc_NumVec, (void*)&args);
    return out;
}

Now calling crashme will successfully destruct obj1 and print the destructor message.

But this is very inconvenient, since I have a series of different Rcpp object allocations taking different constructor types, which would imply either defining a different struct and callback for each one of them, or translating all the calls to lengthy lambda functions.

Is there any way to automatically make all calls to constructors of e.g. Rcpp::NumericVector and Rcpp::IntegerVector have unwind protection?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...