gpt4 book ai didi

c++ - 将 c++ 对象作为指针传递给 Rcpp 中另一个函数的重用

转载 作者:可可西里 更新时间:2023-11-01 17:37:48 25 4
gpt4 key购买 nike

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

// [[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 中返回一个 int 给 R,但是在我原来的代码中,a 是一个有点复杂的数据结构我不想只返回指向它的指针,所以它可以被另一个名为 bar

的 C++ 函数重用
a <- foo()
bar(a)

在这个例子中,我期望 bar(a) 返回 1 而不是 0。我该如何解决这个问题?

最佳答案

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

// [[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++ - 将 c++ 对象作为指针传递给 Rcpp 中另一个函数的重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com