如何将指针从C代码传递到R中的函数(使用外部R),并在R中调用该函数?类似于:
C:
C:
typedef void (* FunctionPtr)();
SEXP ans;
PROTECT(ans = /* ?some code? */);
R_tryEval(ans, R_GlobalEnv, NULL);
UNPROTECT(1);
R:
callback_function()
编辑:
@Romain Francois的帖子非常有帮助。
我的应用程序代码:
namespace
{
void callback()
{
std::cout << "callback\n" << std::flush;
}
}
class Worker
{
public:
/*...*/
void initialize(argc, argv)
{
Rf_initEmbeddedR(argc, argv);
SEXP ans, val;
typedef void (* FunctionPtr)();
PROTECT(ans = Rf_lang2(Rf_install("source"), Rf_mkString("script.R")));
R_tryEval(ans, R_GlobalEnv, NULL);
UNPROTECT(1);
PROTECT(val = Rf_ScalarInteger((int)(&callback)));
/* pass the address of the pointer to a function */
PROTECT(ans = Rf_lang2(Rf_install("setCallback"), val));
R_tryEval(ans, R_GlobalEnv, NULL);
UNPROTECT(2);
}
void uninitialize()
{
Rf_endEmbeddedR(0);
}
};
R和Rcpp
script.R
###################
sourceCpp("utils.cpp")
###################
callback <- function()
{
callCallback()
}
utils.cpp
#include <Rcpp.h>
using namespace Rcpp;
typedef void (* Callback)();
static Callback spCallback = 0;
// [[Rcpp::export]]
void callCallback()
{
if (spCallback) {
spCallback();
} else {
Rprintf("ERROR: callback is not set");
}
}
// [[Rcpp::export]]
void setCallback(const int address)
{
spPlaceOrder = (Callback)address;
}