Peter
Peter

Reputation: 1

cpp11 gives error "object not found" for all c++ functions

I am trying to write a package using C++11 and have succeeded in writing code that runs correctly when sourced with cpp11::cpp_source(). However, when I try to load the functions using devtools, I get an error stating that the function cannot be found: Error in <function> : object <function name> not found.

I used the following sample tutorial to create a minimal example: https://www.r-bloggers.com/2023/05/using-cpp11-r-package-and-llvm-on-ubuntu/. The files I used for the example are:

code.cpp

#include <cpp11.hpp>
#include <cpp11/doubles.hpp>
using namespace cpp11;
    
[[cpp11::register]] doubles_matrix<> Xt(doubles_matrix<> X)
{
    int NX = X.nrow();
    int MX = X.ncol();
    writable::doubles_matrix<> R(MX, NX);
    for (int i = 0; i < MX; i++)
    {
        for (int j = 0; j < NX; j++)
        {
            R(i, j) = X(j, i);
        }
    }
    return R;
}

cpp11dummypackage-package.R

#' @useDynLib cpp11dummypackage, .registration = TRUE
NULL

#' Transpose a matrix
#' @export
#' @rdname Xt
#' @param X numeric matrix
#' @return numeric matrix
#' @examples
#' set.seed(1234)
#' X <- matrix(rnorm(4), nrow = 2, ncol = 2)
#' X
#' cpp11_Xt(X)
cpp11_Xt <- function(X) {
  Xt(X)
}

Running devtools::load_all() appears to run correctly, however, running cpp11_Xt() gives the error:

Error in Xt(X) : object '_cpp11dummypackage_Xt' not found.

I have tried updating R and installing on a different system, but the same error persists.

Upvotes: -1

Views: 140

Answers (1)

Peter
Peter

Reputation: 1

I worked out what I was missing.

The lines

#' @useDynLib cpp11dummypackage, .registration = TRUE
NULL

instruct Roxygen2 to add a line on using DynLib to the NAMESPACE file in the package (which in turn is what loads the C++ functions to be called from R). The NULL is important as otherwise it seems to cause Roxygen2 to skip the comment (this is speculation on my part, but adding it in did fix the problem).

I then needed to run devtools::document() in order to correctly generate the NAMESPACE file.

Upvotes: 0

Related Questions