Reputation: 57
In a .cpp file that I'm editing in RStudio, the following code
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
mat mkGramMatrix (mat X, int n, double (*kernel) (mat, mat, double), double k_param=0){
double (*func_kernel) (mat, mat, double);
func_kernel = kernel;
mat K(n, n);
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
K(i, j) = func_kernel(X.row(i), X.row(j), k_param);
}
}
return K;
}
produces the following error when I try to source inside RStudio:
KFDA_Rcpp.cpp:138:63: error: cannot combine with previous 'type-name' declaration specifier
RcppExport SEXP sourceCpp_32_mkGramMatrix(SEXP XSEXP, SEXP nSEXP, SEXP double)SEXP, SEXP k_paramSEXP) {
^
KFDA_Rcpp.cpp:138:70: error: expected ';' after top level declarator
RcppExport SEXP sourceCpp_32_mkGramMatrix(SEXP XSEXP, SEXP nSEXP, SEXP double)SEXP, SEXP k_paramSEXP) {
^
;
KFDA_Rcpp.cpp:138:74: error: expected unqualified-id
RcppExport SEXP sourceCpp_32_mkGramMatrix(SEXP XSEXP, SEXP nSEXP, SEXP double)SEXP, SEXP k_paramSEXP) {
^
3 errors generated.
Why is it placing a right parenthesis in
SEXP double)SEXP
when I believe I am using the function pointer correctly? I have successfully compiled and used other RcppArmadillo functions without problem but this is the first function I'm making that utilizes a function pointer so I can specify the kernel at the time I call this function.
Upvotes: 0
Views: 465
Reputation: 368489
You cannot put a function pointer in the interface as it is not a type that maps to SEXP
.
We can only call functions from R that map to the .Call()
interface which requires SEXP
arguments --- so we can use types for which we have mappers to and from SEXP
.
The easy way out here is to use Rcpp::XPtr
. It provides an 'external pointer interface' through which you can pass your kernel function. Inside the mkGramMatrix()
function you can then dereference the XPtr
to the functions you want to call. There are several posts here and on the Rcpp Gallery to get you started. It is a great mechanism: hang in there and read up on it.
Upvotes: 1