R/init_cpp.R

Defines functions init_cpp

Documented in init_cpp

#' Register functions implemented in C++
#'
#' If you set up your package using \code{\link{rstan_package_skeleton}} before
#' version \code{1.2.1} of \pkg{rstantools} it may be necessary for you to call
#' this function yourself in order to pass \code{R CMD check} in \R \code{>=
#' 3.4}. If you used \code{rstan_package_skeleton} in \pkg{rstantools} version
#' \code{1.2.1} or later then this has already been done automatically.
#'
#' @export
#' @param name The name of your package as a string.
#' @param path The path to the root directory for your package as a string. If
#'   not specified it is assumed that this is already the current working
#'   directory.
#' @return This function is only called for its side effect of writing the
#'   necessary \code{init.cpp} file to the package's \code{src/} directory.
#'
init_cpp <- function(name, path) {
  file <- file.path("src", "init.cpp")
  if (!missing(path))
    file <- file.path(path, file)

  cat(
    "// Generated by the rstantools package\n\n",
    "#include <R.h>",
    "#include <Rinternals.h>",
    "#include <R_ext/Rdynload.h>",
    "#include <R_ext/Visibility.h>",
    "#include <Rversion.h>",
    sep = "\n",
    file = file,
    append = FALSE
  )

  cat(
    "\n\nstatic const R_CallMethodDef CallEntries[] = {",
    "  {NULL, NULL, 0}",
    "};",
    sep = "\n",
    file = file,
    append = TRUE
  )

  cat(
    paste0("\n\nvoid attribute_visible R_init_", name, "(DllInfo *dll) {"),
    "  // next line is necessary to avoid a NOTE from R CMD check",
    "  R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);",
    "  R_useDynamicSymbols(dll, TRUE); // necessary for .onLoad() to work",
    "}",
    sep = "\n",
    file = file,
    append = TRUE
  )
}
stan-dev/rstantools documentation built on Aug. 21, 2018, 1:10 p.m.