传递c ++对象作为指针,以在Rcpp中的另一个函数中重用 [英] Pass a c++ object as a pointer an reuse in another function in Rcpp

查看:118
本文介绍了传递c ++对象作为指针,以在Rcpp中的另一个函数中重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在C ++中具有以下2个函数:

Suppose a I have the following 2 functions in C++:

// [[Rcpp::export]]
SEXP foo() {

  int a = 1;

  Rcpp::XPtr<int> ptr(&a, true);

  return ptr;
}

// [[Rcpp::export]]
int bar(SEXP a){

  Rcpp::XPtr<int> x(a);
  int b = *x;

  return b;
}

我希望能够在R中调用以下内容。
当然,在此示例中,我可以在 foo 中向R返回 int ,但是在我的原始代码中, a 是一个有点复杂的数据结构,我不想只返回指向它的指针,因此它可以被另一个名为 bar的C ++函数重用。

I want to be able to call something like the following in R. Of course, in this example I could return an int to R in foo, but in my original code, a is a somewhat complex data structure and I wan't to return only the pointer to this, so it can be reused by another C++ function called bar

a <- foo()
bar(a)

在此示例中,我希望 bar(a)返回1而不是0。如何解决此问题?

In this example I expected that bar(a) returned 1 instead of 0. How can I fix this?

推荐答案

您的初始变量 a foo 中完成,c>就超出范围。相反,您需要首先初始化指针,进行分配,然后用 XPtr 包装它。下面显示了如何执行此操作的示例。

Your initial variable a goes out of scope as soon as the function finishes in foo. Instead you need to initialize your pointer first, assign it, then wrap it with the XPtr. The following shows an example of how to do this.

// [[Rcpp::export]]
SEXP foo() {

  int *a = new int(1);

  Rcpp::XPtr<int> ptr(a);

  return ptr;
}

R代码

Rcpp::sourceCpp('test.cpp')

a <- foo()
bar(a)
[1] 1

这篇关于传递c ++对象作为指针,以在Rcpp中的另一个函数中重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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