我正在使用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標籤以及... –