I would like to emulate this example here, but use a method of my own class on an instantiated object. The design choice is that I would like to make a statistical model available in R, having written the core in C++. The oo design is important to that class of problem for memory reasons. In short, it's a likelihood endowed with data and constant parameters, which then gets passed to an optimizer in R.
Because exposing classes in R is tricky when defining cluster environments, I am constructing an object inside this function and wish to return a function pointer to this very object like so:
Typedefs:
typedef std::function<double(int, int) > OrdinaryFunc;
typedef double (*funcPtr)(int a,int b);
And the two functions that collectively should enable a call to a member function:
//' @export
// [[Rcpp::export]]
Rcpp::XPtr<OrdinaryFunc> ofunc(){
MatrixAttempt maus(1,2,true,Eigen::MatrixXd::Zero(800,1),false,false);
//maus.ExtraSetter(1,"Dynamic","Gaussian");
//maus.GetModelType();
OrdinaryFunc ofu = std::bind(&MatrixAttempt::tdens,maus,std::placeholders::_1, std::placeholders::_2);
//return(Rcpp::XPtr<OrdinaryFunc>(new OrdinaryFunc(&ofu)));
return(Rcpp::XPtr<OrdinaryFunc>(&ofu));
}
//' @export
// [[Rcpp::export]]
double callViaXPtr( int a, int b, SEXP xpsexp) {
Rcpp::XPtr<funcPtr> xpfun(xpsexp);
funcPtr fun = *xpfun;
double y = fun(a,b);
return (y);
}
My attempt at a solution was to include a function pointer in my class, which strikes me as unnecessarily hacky. The example provided here helped with creating adequate pointers to instantiated class members, so that it compiles fine. Back home in R, I ran
fun <- ofunc()
and then callViaXPtr(1,2,fun)
which crashed my R session with no error message.
How can I construct an instance of a class inside a wrapper function and return it as a pointer to the R session so that it can be called like a normal function?
Importantly, the function should be exportable to cluster nodes using the parallel
package and not suffer from the lack of recognition as the modules output does.