我正在使用Rcpp和模块将一些用C++编写的MCMC软件转换为R包。在这方面,我需要维护一个全局变量的指针,并指向某个类的最新对象。C++全局变量导致段错误
这里是在R-脚本的形式很简单的例子:
require(Rcpp)
require(inline)
inc <- '
using namespace Rcpp;
class test;
test* glob; //global pointer
class test{
private:
double foo;
public:
test(double foo_) : foo(foo_) {
glob=this; // the line causes segfault
};
double get_foo(){return foo;};
};
RCPP_MODULE(test){
class_<test>("test")
.constructor<double>()
.property("foo",&test::get_foo)
;
}
'
fx <- cxxfunction(signature(),plugin="Rcpp",include=inc);
test_module <- Module("test",getDynLib(fx))
test <- test_module$test
t1 <- new(test,1.0)
我试图让在是类似以下内容(C++):
#include<iostream>
class test;
test* glob;
class test{
private:
double foo;
public:
test(double foo_) : foo(foo_) {glob=this;};
double get_foo(){return foo;};
};
int main(){
test t1(1.0);
test t2(2.0);
std::cout << (*glob).get_foo() << std::endl;
}
它编译和运行,因为它应该。
由于提前, 问候,撕毁Kleppe
添加R标签以及... –