创建一个std :: shared_ptr对象并将其返回到R端(Rcpp) [英] Creating a std::shared_ptr object and returning it to the R side (Rcpp)

查看:364
本文介绍了创建一个std :: shared_ptr对象并将其返回到R端(Rcpp)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Rcpp为C ++脚本编写R绑定。其中一个函数需要一个 std :: shared_ptr对象。我发现难以初始化 std :: shared_ptr obj并将其作为 Rcpp :: XPtr 对象。

I'm trying to write a R bindings for a C++ script using Rcpp. One of the functions expects a std::shared_ptr object. I find it difficult to initialize the std::shared_ptr obj and return it to the R side as a Rcpp::XPtr object.

我试过了(最小例子):

I've tried (minimal example):

#include <iostream>
#include <memory>
#include <Rcpp.h> 
using namespace Rcpp;
using std::cout;


class TestClass {
  public:
    int value;

    TestClass(int initial_val) {
      value = initial_val;
    };

};


//[[Rcpp::export]]
SEXP get_test_obj() {
  Rcpp::XPtr<std::shared_ptr<TestClass>> ptr(std::make_shared<TestClass>(5), true);
  return ptr;
};

但遇到以下错误:

 no matching function for call to 'Rcpp::XPtr<std::shared_ptr<TestClass> >::XPtr(std::shared_ptr<TestClass>, bool)'

去做这个?

推荐答案

我怀疑R端会有一个std :: shared_ptr传递给它。我假设你的源代码中的一些其他代码依赖于std :: shared_ptr,但你想传递内部原始指针到R.我还假设std :: shared_ptr的生命周期更适当地管理你的代码,因为所提供的代码会使std :: shared_ptr超出函数的范围,并在下一个引用中崩溃。

I doubt that the R side would expect to have a std::shared_ptr passed to it. I'm assuming that some other code in your source relies on std::shared_ptr, but you want to pass the inner raw pointer to R. I'm also assuming that the std::shared_ptr's lifetime is more appropriately managed in your code, since the code as presented would make the std::shared_ptr fall out of scope after the function and crash on the next dereference.

在任何情况下,如果你想传递内部原始指针到R,你会这样做(设计):

In any case, if you wanted to just pass the inner raw pointer to R, you'd do it like this (contrived):

//[[Rcpp::export]]
SEXP get_test_obj() {
  std::shared_ptr<TestClass> s_ptr = std::make_shared<TestClass>(5);
  Rcpp::XPtr<TestClass> x_ptr(s_ptr.get(), true);
  return x_ptr;
};

这篇关于创建一个std :: shared_ptr对象并将其返回到R端(Rcpp)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆