Movatterモバイル変換


[0]ホーム

URL:


Title:Seamless R and C++ Integration
Version:1.1.0
Date:2025-07-01
Description:The 'Rcpp' package provides R functions as well as C++ classes which offer a seamless integration of R and C++. Many R data types and objects can be mapped back and forth to C++ equivalents which facilitates both writing of new code as well as easier integration of third-party libraries. Documentation about 'Rcpp' is provided by several vignettes included in this package, via the 'Rcpp Gallery' site athttps://gallery.rcpp.org, the paper by Eddelbuettel and Francois (2011, <doi:10.18637/jss.v040.i08>), the book by Eddelbuettel (2013, <doi:10.1007/978-1-4614-6868-4>) and the paper by Eddelbuettel and Balamuta (2018, <doi:10.1080/00031305.2017.1375990>); see 'citation("Rcpp")' for details.
Imports:methods, utils
Suggests:tinytest, inline, rbenchmark, pkgKitten (≥ 0.1.2)
URL:https://www.rcpp.org,https://dirk.eddelbuettel.com/code/rcpp.html,https://github.com/RcppCore/Rcpp
License:GPL-2 |GPL-3 [expanded from: GPL (≥ 2)]
BugReports:https://github.com/RcppCore/Rcpp/issues
MailingList:rcpp-devel@lists.r-forge.r-project.org
RoxygenNote:6.1.1
Encoding:UTF-8
NeedsCompilation:yes
Packaged:2025-07-01 12:58:41 UTC; edd
Author:Dirk EddelbuettelORCID iD [aut, cre], Romain FrancoisORCID iD [aut], JJ AllaireORCID iD [aut], Kevin UsheyORCID iD [aut], Qiang KouORCID iD [aut], Nathan Russell [aut], Iñaki UcarORCID iD [aut], Doug BatesORCID iD [aut], John Chambers [aut]
Maintainer:Dirk Eddelbuettel <edd@debian.org>
Repository:CRAN
Date/Publication:2025-07-02 16:40:02 UTC

R / C++ interface

Description

TheRcpp package provides C++ classes thatgreatly facilitate interfacing C or C++ code inR packages usingthe.Call interface provided byR.

Introduction

Rcpp provides C++ classes to facilitate manipulation of a largenumber of R data structures : vectors, functions, environments, ...

The “Rcpp-introduction” vignette gives an introduction on the package

Usage for package building

The “Rcpp-package” vignette documents how to use Rcpp in client packages.

History

The initial versions of Rcpp were written by Dominick Samperi during 2005 and2006.

Dirk Eddelbuettel made some additions, and became maintainer in 2008.

Dirk Eddelbuettel and Romain Francois have been extending Rcpp since 2009.

Author(s)

Dirk Eddelbuettel and Romain Francois

References

Dirk Eddelbuettel and Romain Francois (2011).Rcpp: Seamless Rand C++ Integration.Journal of Statistical Software,40(8), 1-18,doi:10.18637/jss.v040.i08. Alsoavailable asvignette("Rcpp-introduction").

Eddelbuettel, Dirk (2013) Seamless R and C++ Integration withRcpp. Springer, New York. ISBN 978-1-4614-6867-7.

See Also

Development forRcpp can be followed via the GitHub repositoryathttps://github.com/RcppCore/Rcpp.

Extensive examples with full documentation are available athttps://gallery.rcpp.org.

Examples

## Not run: # introduction to Rcppvignette("Rcpp-introduction")# information on how to build a package that uses Rcppvignette("Rcpp-package")## End(Not run)

completion

Description

completion

Methods

signature(x = "ANY")
signature(x = "C++Object")

completes fields and methods of C++ objects

signature(x = "Module")

completes functions and classes of modules


Reflection information for an internal c++ class

Description

Information about an internal c++ class.

Objects from the Class

Objects are usually extracted from aModuleusing the dollar extractor.

Slots

.Data:

mangled name of the class

pointer:

external pointer to the internal infomation

module:

external pointer to the module

fields:

list ofC++Field objects

constructors:

list ofC++Constructor objects

methods:

list ofC++OverloadedMethods objects

generator

the generator object for the class

docstring

description of the class

typeid

unmangled typeid of the class

enums

enums of the class

parents

names of the parent classes of this class

Methods

show

signature(object = "C++Class"): prints the class.

$

signature(object = "C++Class"): ...


Class "C++Constructor"

Description

Representation of a C++ constructor

Extends

Class"envRefClass", directly.Class".environment", by class "envRefClass", distance 2.Class"refClass", by class "envRefClass", distance 2.Class"environment", by class "envRefClass", distance 3, with explicit coerce.Class"refObject", by class "envRefClass", distance 3.

Fields

pointer:

pointer to the internal structure that represent the constructor

class_pointer:

pointer to the internal structure that represent the associated C++ class

nargs:

Number of arguments the constructor expects

signature:

C++ signature of the constructor

docstring:

Short description of the constructor


Class "C++Field"

Description

Metadata associated with a field of a class exposed through Rcpp modules

Fields

pointer:

external pointer to the internal (C++) object that represents fields

cpp_class:

(demangled) name of the C++ class of the field

read_only:

Is this field read only

class_pointer:

external pointer to the class this field is from.

Methods

No methods defined with class "C++Field" in the signature.

See Also

Thefields slot of theC++Class class is a list ofC++Field objects

Examples

showClass("C++Field")

Class "C++Function"

Description

Internal C++ function

Objects from the Class

Objects can be created by theRcpp::InternalFunctionclass from theRcpp library

Slots

.Data:

R function that calls back to the internal function

pointer:

External pointer to a C++ object poiting to the function

docstring:

Short documentation for the function

signature:

C++ signature

Extends

Class"function", from data part.Class"OptionalFunction", by class "function", distance 2.Class"PossibleMethod", by class "function", distance 2.

Methods

show

signature(object = "C++Function"): print the object

Examples

showClass("C++Function")

c++ internal objects

Description

C++ internal objects instanciated from a class exposed in an Rcpp module

Objects from the Class

This is a virtual class. Actual C++ classes are subclasses.

Methods

$

signature(x = "C++Object"): invokes a method on the object, or retrieves the value of a property

$<-

signature(x = "C++Object"): set the value of a property

show

signature(object = "C++Object"): print the object


Class "C++OverloadedMethods"

Description

Set of C++ methods

Extends

Class"envRefClass", directly.Class".environment", by class "envRefClass", distance 2.Class"refClass", by class "envRefClass", distance 2.Class"environment", by class "envRefClass", distance 3, with explicit coerce.Class"refObject", by class "envRefClass", distance 3.

Fields

pointer:

Object of classexternalptr pointer to the internal structure that represents the set of methods

class_pointer:

Object of classexternalptr pointer to the internal structure that models the related class


Deprecated Rcpp Linker Flags

Description

In Rcpp versions prior to release 0.10.1 of November 2013,LdFlags andRcppLdFlags were used to return the requiredflags and options for the system linker to link to the Rcpp userlibrary. Since we no longer build or ship a user library, thesefunctions now return an empty string. As of Rcpp release 0.12.19,these functions are now deprecated.

Usage

  LdFlags()  RcppLdFlags()

Value

An empty string.

Author(s)

Dirk Eddelbuettel and Romain Francois

References

Dirk Eddelbuettel and Romain Francois (2011).Rcpp: Seamless Rand C++ Integration.Journal of Statistical Software,40(8), 1-18,doi:10.18637/jss.v040.i08. Alsoavailable asvignette("Rcpp-introduction").


Retrieves an Rcpp module

Description

Retrieves an Rcpp module from a dynamic library, usually associated with a package.

Usage

Module(module, PACKAGE = , where = , mustStart =  )

Arguments

module

Name of the module, as declared in theRCPP_MODULE macro internally

PACKAGE

Passed togetNativeSymbolInfo

where

When the module is loaded, S4 classes are defined based on the internal classes. This argument is passed tosetClass

mustStart

TODO

Value

An object of classModule collecting functions and classes declared in the module.


Rcpp modules

Description

Collection of internal c++ functions and classes exposed to R

Objects from the Class

modules are created by thelink{Module} function

Methods

$

signature(x = "Module"): extract a function or a class from the module.

prompt

signature(object = "Module"): generates skeleton of a documentation for a Module.

show

signature(object = "Module"): summary information about the module.

initialize

signature(.Object = "Module"): ...

See Also

TheModule function


Deprecated Functions in the Rcpp Package

Description

These functions are provided for compatibility with older versions of theRcpp package only, and may be removed in future versions.

Details

Author(s)

Dirk Eddelbuettel and Romain Francois


Rcpp internal functions

Description

TheRcpp utilizes several internal functions whichneed to visible within its namespace, yet are not user-facing. Thispage provides basic documentation for them.

Usage

  cpp_object_initializer(.self, .refClassDef, ..., .object_pointer)  cpp_object_dummy(.self, .refClassDef)

Arguments

.self

A reference to the object being modified

.refClassDef

The definition of a reference class

...

Further arguments

.object_pointer

Optional external pointer


Create a skeleton for a new package depending on Rcpp

Description

Rcpp.package.skeleton automates the creation ofa new source package that intends to use features of Rcpp.

It is based on thepackage.skeleton functionwhich it executes first.

Usage

Rcpp.package.skeleton(name = "anRpackage", list = character(),environment = .GlobalEnv, path = ".", force = FALSE,code_files = character(), cpp_files = character(),example_code = TRUE, attributes = TRUE, module = FALSE,author = "Your Name",maintainer = if(missing( author)) "Your Name" else author,email = "your@email.com", githubuser = NA_character_,license = "GPL (>= 2)")

Arguments

name

Seepackage.skeleton

list

Seepackage.skeleton

environment

Seepackage.skeleton

path

Seepackage.skeleton

force

Seepackage.skeleton

code_files

Seepackage.skeleton

cpp_files

A character vector with the paths to C++ source files to add to the package.

example_code

If TRUE, example c++ code using Rcpp is added to the package.

attributes

If TRUE, example code makes use of Rcpp attributes.

module

If TRUE, an exampleModule is added to the skeleton.

author

Author of the package.

maintainer

Maintainer of the package.

email

Email of the package maintainer.

githubuser

GitHub username for URL and BugReports, if present.

license

License of the package.

Details

In addition topackage.skeleton :

The ‘⁠DESCRIPTION⁠’ file gains an Imports line requesting thatthe package depends on Rcpp and a LinkingTo line so that the packagefinds Rcpp header files.

The ‘⁠NAMESPACE⁠’ gains auseDynLib directive as wellas animportFrom(Rcpp, evalCpp to ensure instantiation of Rcpp.

The ‘⁠src⁠’ directory is created if it does not exists.

Ifcpp_files are provided then they will be copied to the ‘⁠src⁠’directory.

If theexample_code argument is set toTRUE,example files ‘⁠rcpp_hello_world.h⁠’ and ‘⁠rcpp_hello_world.cpp⁠’are also created in the ‘⁠src⁠’. An R file ‘⁠rcpp_hello_world.R⁠’ isexpanded in the ‘⁠R⁠’ directory, thercpp_hello_world functiondefined in this files makes use of the C++ function ‘⁠rcpp_hello_world⁠’defined in the C++ file. These files are given as an example and shouldeventually by removed from the generated package.

If theattributes argument isTRUE, then rather than generatethe example files as described above, a single ‘⁠rcpp_hello_world.cpp⁠’file is created in the ‘⁠src⁠’ directory and it's attributes arecompiled using thecompileAttributes function. This leads tothe files ‘⁠RcppExports.R⁠’ and ‘⁠RcppExports.cpp⁠’ being generated.They are automatically regenerated fromscratch each timecompileAttributes is called. Therefore, one shouldnot modify by hand either of the ‘⁠RcppExports⁠’ files.

If themodule argument isTRUE, a sample Rcpp module willbe generated as well.

Value

Nothing, used for its side effects

References

Read theWriting R Extensions manual for more details.

Once you have created asource package you need to install it:see theR Installation and Administration manual,INSTALL andinstall.packages.

See Also

package.skeleton

Examples

## Not run: # simple packageRcpp.package.skeleton( "foobar" )# package using attributesRcpp.package.skeleton( "foobar", attributes = TRUE )# package with a moduleRcpp.package.skeleton( "testmod", module = TRUE )# the Rcpp-package vignettevignette( "Rcpp-package" )# the Rcpp-modules vignette for information about modulesvignette( "Rcpp-modules" )## End(Not run)

Facilitating making package plugins

Description

This function helps packages making inline plugins.

Usage

Rcpp.plugin.maker(  include.before = "",   include.after = "",   LinkingTo = unique(c(package, "Rcpp")),   Depends = unique(c(package, "Rcpp")),   Imports = unique(c(package, "Rcpp")),   libs = "",   Makevars = NULL,   Makevars.win = NULL,   package = "Rcpp")

Arguments

include.before

Code to be included before the ‘⁠Rcpp.h⁠’ file

include.after

Code to be included after the ‘⁠Rcpp.h⁠’ file

LinkingTo

Packages to be added to the ‘⁠LinkingTo⁠’ field

Depends

Packages to be added to the ‘⁠Depends⁠’ field [deprecated]

Imports

Packages to be added to the ‘⁠Depends⁠’ field

libs

library flags

Makevars

content for a ‘⁠Makevars⁠’ file, orNULL

Makevars.win

content for a ‘⁠Makevars.win⁠’ file, orNULL

package

The package this plugin is for.

Value

A function that is suitable as a plugin. See for example the ‘⁠RcppArmadillo⁠’ package that uses this to create its inline plugin.


Rcpp : unit tests results

Description

Unit tests results for package Rcpp.

Unit tests are run automatically at build time and reports are included in the‘⁠doc⁠’ directory as html or text.

See Also

../doc/unitTests-results/Rcpp-unitTests.html: html formatted unit test report

Examples

# unit tests are in the unitTests directory of the packagelist.files( system.file("unitTests", package = "Rcpp" ),pattern = "^runit", full = TRUE )# trigger the unit tests preparation, follow printed instructions# on how to run them## Not run: source( system.file("unitTests", "runTests.R", package = "Rcpp" ) )## End(Not run)

Compile Rcpp Attributes for a Package

Description

Scan the source files within a package for attributes and generate code as required. Generates the bindings required to call C++ functions from R for functions adorned with theRcpp::export attribute.

Usage

compileAttributes(pkgdir = ".", verbose = getOption("verbose"))

Arguments

pkgdir

Directory containing the package to compile attributes for (defaults to the current working directory).

verbose

TRUE to print detailed information about generated code to the console.

Details

The source files in the package directory given bypkgdir are scanned for attributes and code is generated as required based on the attributes.

For C++ functions adorned with theRcpp::export attribute, the C++ and R source code required to bind to the function from R is generated and added (respectively) tosrc/RcppExports.cpp orR/RcppExports.R. Both of these files are automatically generated fromscratch each timecompiledAttributes is run.

In order to access the declarations for customRcpp::as andRcpp::wrap handlers thecompileAttributes function will also call anyinline plugins available for packages listed in theLinkingTo field of theDESCRIPTION file.

Value

Returns (invisibly) a character vector with the paths to any files that were updated as a result of the call.

Note

ThecompileAttributes function deals only with exporting C++ functions to R. If you want the functions to additionally be publicly available from your package's namespace another step may be required. Specifically, if your packageNAMESPACE file does not use a pattern to export functions then you should add an explicit entry toNAMESPACE for each R function you want publicly available.

In addition to exporting R bindings for C++ functions, thecompileAttributes function can also generate a direct C++ interface to the functions using theRcpp::interfaces attribute.

See Also

Rcpp::export,Rcpp::interfaces

Examples

## Not run: # Compile attributes for package in the current working dircompileAttributes()## End(Not run)

Check for Minimal (g++) Compiler Version

Description

Helper function to establish minimal compiler versions, currently limitedonly tog++ which (particularly for older RHEL/CentOS releases) istoo far behind current C++11 standards required for some packages.

Usage

compilerCheck(minVersion = package_version("4.6.0"))

Arguments

minVersion

An object of typepackage_version, with a defaultof version 4.6.0

Details

This function looks upg++ (as well as optional values in theCXX andCXX1X environment variables) in thePATH. Forall values found, the output ofg++ -v is analyzed for the versionstring, which is then compared to the given minimal version.

Value

A boolean value is returned, indicating if the minimal version isbeing met

Author(s)

Dirk Eddelbuettel


Define an R Function with a C++ Implementation

Description

Dynamically define an R function with C++ source code. Compiles and links a shared library with bindings to the C++ function then defines an R function that uses.Call to invoke the library.

Usage

cppFunction(code, depends = character(), plugins = character(), includes = character(),            env = parent.frame(), rebuild = FALSE, cacheDir = getOption("rcpp.cache.dir",            tempdir()), showOutput = verbose, verbose = getOption("verbose"), echo = TRUE)

Arguments

code

Source code for the function definition.

depends

Character vector of packages that the compilation depends on. Each package listed will first be queried for aninline plugin to determine header files to include. If no plugin is defined for the package then a header file based the package's name (e.g.PkgName.h) will be included.

plugins

Character vector ofinline plugins to use for the compilation.

includes

Character vector of user includes (inserted after the includes provided bydepends).

env

Theenvironment in which to define the R function. May beNULL in which case the defined function can be obtained from the return value ofcppFunction.

rebuild

Force a rebuild of the shared library.

cacheDir

Directory to use for caching shared libraries. If the underlying code passed tosourceCpp has not changed since the last invocation then a cached version of the shared library is used. The default value oftempdir() results in the cache being valid only for the current R session. Pass an alternate directory to preserve the cache across R sessions.

showOutput

TRUE to printR CMD SHLIB output to the console.

verbose

TRUE to print detailed information about generated code to the console.

echo

TRUE to silence output from optional R evaluation if set toFALSE.

Details

Functions defined usingcppFunction must have return types that are compatible withRcpp::wrap and parameter types that are compatible withRcpp::as.

The shared library will not be rebuilt if the underlying code has not changed since the last compilation.

Value

An R function that uses.Call to invoke the underlying C++ function.

Note

You can also define R functions with C++ implementations using thesourceCpp function, which allows you to separate the C++ code into it's own source file. For many use cases this is an easier and more maintainable approach.

See Also

sourceCpp,evalCpp

Examples

## Not run: cppFunction(    'int fibonacci(const int x) {        if (x == 0) return(0);        if (x == 1) return(1);        return (fibonacci(x - 1)) + fibonacci(x - 2);    }')cppFunction(depends = "RcppArmadillo",    'List fastLm(NumericVector yr, NumericMatrix Xr) {        int n = Xr.nrow(), k = Xr.ncol();        arma::mat X(Xr.begin(), n, k, false);        arma::colvec y(yr.begin(), yr.size(), false);        arma::colvec coef = arma::solve(X, y);        arma::colvec resid = y - X*coef;        double sig2 = arma::as_scalar(arma::trans(resid)*resid/(n-k) );        arma::colvec stderrest = arma::sqrt(            sig2 * arma::diagvec(arma::inv(arma::trans(X)*X)));        return List::create(Named("coefficients") = coef,            Named("stderr")       = stderrest        );    }')cppFunction(plugins=c("cpp11"), '    int useCpp11() {        auto x = 10;        return x;    }')## End(Not run)

c++ type information

Description

demangle gives the demangled type,sizeof its size (in bytes).

Usage

    demangle(type = "int", ...)    sizeof(type = "int", ...)

Arguments

type

The type we want to demangle

...

Further argument forcppFunction

Details

The following function is compiled and invoked:

        SEXP demangle_this_type(){            typedef             return wrap( DEMANGLE(type) ) ;        }                SEXP sizeof_this_type(){            typedef             return wrap( sizeof(type) ) ;        }

DEMANGLE is a macro in ‘⁠Rcpp⁠’ that does the work.

Value

The demangled type, as a string.

Note

We only know how to demangle with gcc. If you know how to demangle typeswith your compiler, let us know.

Author(s)

Romain Francois <romain@r-enthusiasts.com>

References

See thischapterfrom the GNU C++ library manual.

See Also

cppFunction is used to compile the functiondemangle creates.

Examples

## Not run:     demangle( "int64_t" )    demangle( "uint64_t" )    demangle( "NumericVector" )    demangle( "std::map<std::string,double>" )        sizeof( "long" )    sizeof( "long long" )    ## End(Not run)

Rcpp::depends Attribute

Description

TheRcpp::depends attribute is added to a C++ source file to indicate that it has a compilation dependency on one or more other packages. For example:

// [[Rcpp::depends(RcppArmadillo)]]

Arguments

...

Packages which the source file depends on for compilation

Details

TheRcpp::depends attribute is used by the implementation of thesourceCpp function to correctly setup the build environment forR CMD SHLIB.

The include directories of the specified packages are added to theCLINK_CPPFLAGS environment variable. In addition, if the referenced package provides aninline plugin it is called to determine additional environment variables required to successfully build.

Note

TheRcpp::depends attribute is specified using a syntax compatible with the newgeneralized attributes feature of the C++11 standard. Note however that since this feature is not yet broadly supported by compilers it needs to be specified within a comment (see examples below).

See Also

sourceCpp

Examples

## Not run: // [[Rcpp::depends(RcppArmadillo)]]// [[Rcpp::depends(Matrix, RcppGSL)]]## End(Not run)

Evaluate a C++ Expression

Description

Evaluates a C++ expression. This creates a C++ function usingcppFunction and calls it to get the result.

Usage

evalCpp(code, depends = character(), plugins = character(), includes = character(),        rebuild = FALSE, cacheDir = getOption("rcpp.cache.dir", tempdir()),        showOutput = verbose, verbose = getOption("verbose"))areMacrosDefined(names, depends = character(), includes = character(),        rebuild = FALSE, showOutput = verbose,        verbose = getOption("verbose"))

Arguments

code

C++ expression to evaluate

names

names of the macros we want to test

plugins

seecppFunction

depends

seecppFunction

includes

seecppFunction

rebuild

seecppFunction

cacheDir

Directory to use for caching shared libraries. If the underlying code passed tosourceCpp has not changed since the last invocation then a cached version of the shared library is used. The default value oftempdir() results in the cache being valid only for the current R session. Pass an alternate directory to preserve the cache across R sessions.

showOutput

seecppFunction

verbose

seecppFunction

Value

The result of the evaluated C++ expression.

Note

The result type of the C++ expression must be compatible withRcpp::wrap.

See Also

sourceCpp,cppFunction

Examples

## Not run: evalCpp("__cplusplus")evalCpp("std::numeric_limits<double>::max()")# areMacrosDefined is no longer exported but accessible via ':::'Rcpp:::areMacrosDefined(c("__cplusplus", "RCPP_VERSION"))## End(Not run)

Rcpp::export Attribute

Description

TheRcpp::export attribute is added to a C++ function definition to indicate that it should be made available as an R function. ThesourceCpp andcompileAttributes functions process theRcpp::export attribute by generating the code required to call the C++ function from R.

Arguments

name

Specify an alternate name for the generated R function (optional, defaults to the name of the C++ function if not specified).

Details

Functions marked with theRcpp::export attribute must meet several conditions to be correctly handled:

  1. Be defined in the global namespace (i.e. not within a C++namespace declaration).

  2. Have a return type that is either void or compatible withRcpp::wrap and parameter types that are compatible withRcpp::as (see sections 3.1 and 3.2 of theRcpp-introduction vignette for more details).

  3. Use fully qualified type names for the return value and all parameters. However, Rcpp types may appear without the namespace qualifier (i.e.DataFrame is okay as a type name butstd::string must be specified fully).

If default argument values are provided in the C++ function definition then these defaults are also used for the exported R function. For example, the following C++ function:

DataFrame readData(    CharacterVector file,    CharacterVector exclude = CharacterVector::create(),    bool fill = true)

Will be exported to R as:

function (file, exclude = character(0), fill = TRUE)

Note that C++ rules for default arguments still apply: they must occur consecutively at the end of the function signature and unlike R can't rely on the values of other arguments.

Note

When a C++ function has export bindings automatically generated by thecompileAttributes function, it can optionally also have a direct C++ interface generated using theRcpp::interfaces attribute.

o TheRcpp::export attribute is specified using a syntax compatible with the newgeneralized attributes feature of the C++11 standard. Note however that since this feature is not yet broadly supported by compilers it needs to be specified within a comment (see examples below).

See Also

sourceCpp andcompileAttributes

Examples

## Not run: #include <Rcpp.h>using namespace Rcpp;// [[Rcpp::export]]int fibonacci(const int x) {   if (x == 0) return(0);   if (x == 1) return(1);   return (fibonacci(x - 1)) + fibonacci(x - 2);}// [[Rcpp::export("convolveCpp")]]NumericVector convolve(NumericVector a, NumericVector b) {   int na = a.size(), nb = b.size();   int nab = na + nb - 1;   NumericVector xab(nab);   for (int i = 0; i < na; i++)      for (int j = 0; j < nb; j++)         xab[i + j] += a[i] * b[j];   return xab;}## End(Not run)

Create an Rcpp Module to Expose a C++ Class in R

Description

The arguments specify a C++ class and some combination ofconstructors, fields and methods to be shared withR by creating acorresponding reference class inR.The information needed in the call toexposeClass() is thesimplest possible in order to create a C++ module for the class; forexample, fields and methods in this class need only be identified bytheir name.Inherited fields and methods can also be included, but moreinformation is needed.The function writes a C++ source file,containing a module definition to expose the class toR, plus one line ofR source to create the corresponding referenceclass.

Usage

exposeClass(class, constructors = , fields = , methods = , file = ,    header = , module = , CppClass = class, readOnly = , rename = ,    Rfile = TRUE)

Arguments

class

The name of the class inR. By default, this will be the same as thename of the class in C++, unless argumentCppClass is supplied.

constructors

A list of the signatures for any of the class constructors to becalled fromR. Each element of the list gives the data types in C++for the arguments to the corresponding constructor. See Details andthe example.

fields,methods

The vector of names for the fields and for the methods to be exposedinR. For inherited fields and methods, type information needs to besupplied; see the section “Inherited Fields and Methods”.

file

Usually, the name for the file on which to write the C++ code, by defaultpaste0(CppClass, "Module.cpp").If the current working directory inR is the top-leveldirectory for a package, the function writes the file in the"src" subdirectory.Otherwise the file is written in the working directory.

The argument may also be a connection, already open for writing.

header

Whatever lines of C++ header information are needed to include thedefinition of the class. Typically this includes a file from thepackage where we are writing the module definition, as in the example below.

module

The name for the Rcpp module, by defaultpaste0("class_",CppClass).

CppClass

The name for the class in C++. By default and usually, the intendedclass name inR.

readOnly

Optional vector of field names. These fields will be created asread-only in the interface.

rename

Optional named character vector, used to name fields or methodsdifferently inR from their C++ name. The elements of the vector arethe C++ names and the corresponding elements ofnames(rename)the desired names inR. Soc(.age = "age") renames the C++field or methodage as.age.

Rfile

Controls the writing of a one-lineR command to create the referenceclass corresponding to the C++ module information. By default, thiswill be a filepaste0(class, "Class.R").If the working directory is anR package sourcedirectory, the file will be written in theR subdirectory, otherwise in the working directory itself.

Supplying a character string substitutes that file name for thedefault.

The argument may also be a connection open forwriting orFALSE to suppress writing theR source altogether.

Details

The file created by the call to these functions only depends on theinformation in the C++ class supplied. This file is intended to bepart of the C++ source for anR package. The file only needs tomodified when the information changes, either because the class haschanged or because you want to expose different information toR. Inthat case you can either recallexposeClass() or edit the C++file created.

The Rcpp Module mechanism has a number of other optional techniques,not covered byexposeClass(). These should be entered into theC++ file created. See the “rcpp-modules” vignette with thepackage for current possibilities.

For fields and methods specified directly in the C++ class,the fields and method arguments toexposeClass() are character vectors naming thecorresponding members of the class. For module construction, thedata types of directly specified fields and of the arguments for the methods are notneeded.

Forinherited fields or methods, data type information isneeded. See the section “Inherited Fields and Methods”.

For exposing class constructors, the module needs to know thesignatures of the constructors to be exposed; each signature is acharacter vector of the corresponding C++ data types.

Value

Nothing, called for its side effect.

Inherited Fields and Methods

If the C++ class inherits from one or more other classes, the standardRcppModule mechanism can not be used to expose inheritedfields or methods.An indirect mechanism is used, generating free functions in C++ toexpose the inherited members inR.

This mechanism requires data type information in the call toexposeClass().This is provided by naming the corresponding element of thefields ormethods argument with the name of the member.The actual element of thefields argument is then the singledata type of the field.

For themethods argument the argument will generally need to bea named list.The corresponding element of the list is the vector of data types forthe return value and for the arguments, if any, to the method.For example, if C++ methodfoo() took a single argument of typeNumericVector and returned a value of typelong, themethods argument would belist(foo = c("long", "NumericVector")).

See the second example below.

Author(s)

John Chambers

See Also

setRcppClass, which must be called from someR sourcein the package.

Examples

## Not run: ### Given the following C++ class, defined in file PopBD.h,### the call to exposeClass() shown below will write a file### src/PopBDModule.cpp containing a corresponding module definition.###   class PopBD {###     public:###       PopBD(void);###       PopBD(NumericVector initBirth, NumericVector initDeath);###   ###       std::vector<double> birth;###       std::vector<double> death;###       std::vector<int> lineage;###       std::vector<long> size;###       void evolve(int);###   ###   };### A file R/PopBDClass.R will be written containing the one line:###   PopBD <- setRcppClass("PopBD")###### The call below exposes the lineage and size fields, read-only,### and the evolve() method.exposeClass("PopBD",      constructors =        list("", c("NumericVector", "NumericVector")),      fields = c("lineage", "size"),      methods = "evolve",      header = '#include "PopBD.h"',      readOnly = c("lineage", "size"))### Example with inheritance:  the class PopCount inherits from ### the previous class, and adds a method table().  It has the same### constructors as the previous class.### To expose the table() method, and the inherited evolve() method and size field:exposeClass("PopCount",      constructors =        list("", c("NumericVector", "NumericVector")),      fields = c(size = "std::vector<long>"),      methods = list("table", evolve = c("void", "int")),      header = '#include "PopCount.h"',      readOnly = "size")## End(Not run)

Set the formal arguments of a C++ function

Description

Set the formal arguments of a C++ function

Methods

signature(fun = "C++Function")

Set the formal arguments of a C++ function


Export the Rcpp (API) Package Version

Description

Helper function to report the package version of the R installation.

Usage

getRcppVersion(devel = FALSE)

Arguments

devel

An logical value indicating if the development orrelease version number should be returned, default is release.

Details

WhilepackageVersion(Rcpp) exports the version registers inDESCRIPTION, this version does get incremented more easilyduring development and can therefore be higher than the releasedversion. The actual#define long used at the C++ levelcorresponds more to an ‘API Version’ which is now providedby this function, and use for example in the package skeletongenerator.

Value

Apackage_version object with either the releaseor development version.

Author(s)

Dirk Eddelbuettel

See Also

packageVersion,Rcpp.package.skeleton

Examples

getRcppVersion()

Rcpp::interfaces Attribute

Description

TheRcpp::interfaces attribute is added to a C++ source file to specify which languages to generate bindings for from exported functions. For example:

// [[Rcpp::interfaces(r, cpp)]]

Arguments

...

Interfaces to generate for exported functions within the source file. Valid values arer andcpp, and more than one interface can be specified.

Details

TheRcpp::interfaces attribute is used to determine which bindings to generate for exported functions. The default behavior if noRcpp::interfaces attribute is specified is to generate only an R interface.

Whencpp bindings are requested code is generated as follows:

  1. Bindings are generated into a header file located in theinst/include directory of the package using the naming conventionPackageName_RcppExports.h

  2. If not already present, an additional header file namedPackageName.h is also generated which in turn includes the Rcpp exports header.

    In the case that you already have aPackageName.h header for your package then you can manually add an include of the Rcpp exports header to it to make the exported functions available to users of your package.

  3. The generated header file allows calling the exported C++ functions without any linking dependency on the package (this is based on using theR_RegisterCCallable andR_GetCCallable functions).

  4. The exported functions are defined within a C++ namespace that matches the name of the package.

For example, an exported C++ functionfoo could be called from packageMyPackage as follows:

   // [[Rcpp::depends(MyPackage)]]   #include <MyPackage.h>   void foo() {      MyPackage::bar();   }

The above example assumes that thesourceCpp function will be used to compile the code. If rather than that you are building a package then you don't need to include theRcpp::depends attribute, but instead should add an entry for the referenced package in theDepends andLinkingTo fields of your package'sDESCRIPTION file.

Note

If a file by the name ofPackageName.h that wasn't generated bycompileAttributes already exists in in theinst/include directory then it will not be overwritten (rather, an error will occur).

A static naming scheme for generated header files and namespaces is used to ensure consistent usage semantics for clients of exportedcpp interfaces. Packages that wish to export more complex interfaces or additional C++ types are therefore typically better off not using this mechanism.

TheRcpp::interfaces attribute is specified using a syntax compatible with the newgeneralized attributes feature of the C++11 standard. Note however that since this feature is not yet broadly supported by compilers it needs to be specified within a comment (see examples below).

See Also

compileAttributes,Rcpp::export,Rcpp::depends

Examples

## Not run: // [[Rcpp::interfaces(r, cpp)]]## End(Not run)

Load an Rcpp Module into a Package

Description

One or more calls toloadModule will be included in the sourcecode for a package to load modules and optionally expose objects fromthem. The actual extraction of the module takes place at load time.

Usage

loadModule(module, what = , loadNow, env =)

Arguments

module

The name of the C++ module to load. The code for the module should bein the same package as theR call toloadModule.

what

The objects to expose in the package's namespace corresponding toobjects in the module. By default, nothing is exposed.

The special valueTRUE says to load all the objects in themodule that have syntactically standardR names (which all objectsin a module will normally have).

Otherwise, if supplied this should be a character vector, the elements beingobjects defined in the module. The vector can have a names attribute,in which case the non-empty names will be used to rename the objects;otherwise, the name of the object in the package namespace will be thesame as the name in the C++ module.

loadNow,env

A logical flag to say whether the load actions should happen now, andthe environment into which the objects should be inserted. Whencalled from the source of a package, both of these arguments shouldusually be omitted.

The value ofloadNow will be set by checking the module'sstatus. At package installation time, the module cannot be started,in which case a load action (seesetLoadAction) isscheduled to do the actual module load.

The value ofenv will default to the package's namespace.

Details

If the purpose of loading the module is to define classes based on C++classes, seesetRcppClass(), which does the necessarymodule loading for you.

When the module can be started (at namespace load time), the functionModule() returns an environment with a description ofthe module's contents. FunctionloadModule() saves this as ametadata object in the package namespace. Therefore multiple calls toloadModule() are an efficient way to extract different objectsfrom the module.

Requesting an object that does not exist in the module produces awarning.

Since assignments from the call cannot take place until namespaceloading time, any computations using the objects must also bepostponed until this time. Use load actions(setLoadAction) and make sure that the load action isspecified after the call toloadModule().

Value

If the load takes place, the module environment is returned. Usuallyhowever the function is called for its side effects.

Note

This function requires version 2.15.0 ofR or later, in order touse load actions, introduced in that version. See the note in thehelp page forsetRcppClass() for details.

Author(s)

John Chambers

See Also

setRcppClass() to avoid the explicit call.

loadRcppModules() for a (deprecated) shotgun procedure to load allmodules.

Examples

## Not run: loadModule("yada", TRUE) # load all the objects from module "yada"## End(Not run)

Loads Rcpp modules on package startup

Description

Note: As of release 0.12.5, this function is deprecated;loadModule should be used instead.

Function to simplify loading Rcpp modules contained in a package.This function must be called from the.onLoad function of a package.It uses theRcppModules field of the packageDESCRIPTION fileto query the names of the modules that the package should export, loads each module,andpopulate each module into the package NAMESPACE.

Usage

  loadRcppModules(direct=TRUE)

Arguments

direct

ifTRUE the content of the module is exposed in thenamespace. Otherwise, the module is exposed.

See Also

populate,loadModule


Rcpp::plugins Attribute

Description

TheRcpp::plugins attribute is added to a C++ source file to specify theinline plugins that should be used in the compilation.

// [[Rcpp::plugins(plugin1, plugin2)]]

Arguments

...

Plugins to add to the compilation.

Details

Plugins must be registered using theregisterPluginfunction.

When included within asourceCpp translation unit,the configuration-related fields of the plugin (e.g.env andLinkingTo) are utilized, however the code-generation fields(e.g.includes andbody) are not.

Note

Rcpp includes a built-incpp11 plugin thatadds the flags required to enableC++11 features in the compiler.

See Also

registerPlugin

Examples

## Not run: // [[Rcpp::plugins(cpp11)]]// [[Rcpp::export]]int useCpp11() {    auto x = 10;    return x;}## End(Not run)

Populates a namespace or an environment with the content of a module

Description

Populates a namespace or an environment with the content of a module

Usage

populate(module, env)

Arguments

module

Rcpp module

env

environment or namespace


Register an inline plugin

Description

Register aninline plugin for use withsourceCpp orcppFunction. Inline plugins are functionsthat return a list with additional includes, environment variables, andother compilation context.

Usage

registerPlugin(name, plugin)

Arguments

name

Name of the inline plugin

plugin

Inline plugin function

Details

Plugins can be added tosourceCpp compilations using theRcpp::plugins attribute.

See Also

Rcpp::plugins


Create a Class Extending a C++ Class

Description

These routines create a class definition inR for an exposed C++class, setting up and executing a load action to incorporate the C++pointer information.Neither function should normally need to be called directly; for most applications,a call toexposeClass() will create both C++ andR code files toexpose the C++ class.

Usage

setRcppClass(Class, CppClass = , module = , fields = list(), contains = ,             methods = , saveAs = Class, where = , ...)loadRcppClass(Class, CppClass = , module = , fields = character(),              contains = character(),              methods = , saveAs = Class, where = , ...)

Arguments

Class

The name for the new class.

CppClass

The C++ class defined in the C++ code for the package that this classextends. By default, the same asClass.

module

The Rcpp module in which the class is defined. The module does nothave to be loaded separately;setRcppClass() will arrange toload the module. By default,"class_" followed by the C++ classname.

IfexposeClass() has been called, the necessary modulecode will have been written in thesrc directory of the package.

fields,contains,methods

Additional fields, superclasses and method definitions inR thatextend the C++ class. These arguments are passed on tosetRefClass().

saveAs

Save a generator object for the class in the package's namespace underthis name. By default, the generator object has the name of theclass. To avoid saving any generator object, supply this argument asNULL.

(This argument is currently needed because the actual class definitionmust take place at package load time, to include C++ pointerinformation.Therefore thevalue returned bysetRcppClass() when called during packageinstallation is not the generator object returned bysetRefClass().We may be able to hackaround this problem in the future.)

where

The environment in which to save the class definition. By default,will be the namespace of the package in which thesetRcppClass() call is included.

...

Arguments, if any, to pass on tosetRefClass().

Details

The call to these functions normally appears in the source code for apackage; in particular, a call is written in anR source file whenexposeClass() is called.

R code for this class or (preferably) a subclass can define new fields and methods for the class.Methods for theR class can refer to methods and fields defined inC++ for the C++ class, if those have been exposed.

The fields and methods defined caninclude overriding C++ fields or methods.Keep in mind, however, thatR methods can refer to C++ fields andmethods, but not the reverse.If you override a C++ field or method, you essentially need to reviseall code that refers to that field or method.Otherwise, the C++ code will continue to use the old C++ definition.

Value

At load time, a generator for the new class is created and storedaccording to thesaveAs argument, typically under the name ofthe class.

The value returned at installation time is a dummy. Future revisionsof the function may allow us to return a valid generator at installtime. We recommend using the standard style of assigning the valueto the name of the class, as one would do withsetRefClass.

Note

This function and functionloadModule() requireversion 2.15.0 ofR or later, in order touse load actions, introduced in that version.

A subtle way this can fail is by somehow loading a legitimatebinary version of your package (installed under a valid version ofR) into a session with an olderR.In this case the load actions created in the binary package willsimply not be called. None of the modules will be loaded and none ofthe classes created.

If your symptom is that classes or other objects from modules don'texist, check theR version.

Author(s)

John Chambers

Examples

## Not run: setRcppClass("World",     module = "yada",     fields = list(more = "character"),    methods = list(        test = function(what) message("Testing: ", what, "; ", more)),    saveAs = "genWorld"         )## End(Not run)

Source C++ Code from a File or String

Description

sourceCpp parses the specified C++ file or source code and looks for functions marked with theRcpp::export attributeand RCPP_MODULE declarations. A shared library is then built and its exported functions and Rcpp modules are made available in the specified environment.

Usage

sourceCpp(file = "", code = NULL, env = globalenv(), embeddedR = TRUE, rebuild = FALSE,          cacheDir = getOption("rcpp.cache.dir", tempdir()), cleanupCacheDir = FALSE,          showOutput = verbose, verbose = getOption("verbose"), dryRun = FALSE,          windowsDebugDLL = FALSE, echo = TRUE)

Arguments

file

A character string giving the path name of a file

code

A character string with source code. If supplied, the code is taken from this string instead of a file.

env

Environment where the R functions and modules should be made available.

embeddedR

TRUE to run embedded R code chunks.

rebuild

Force a rebuild of the shared library.

cacheDir

Directory to use for caching shared libraries. If the underlying file or code passed tosourceCpp has not changed since the last invocation then a cached version of the shared library is used. The default value oftempdir() results in the cache being valid only for the current R session. Pass an alternate directory to preserve the cache across R sessions.

cleanupCacheDir

Cleanup all files in the cacheDir that were not a result of this compilation. Note that this will cleanup the cache from all other calls to sourceCpp with the same cacheDir. This option should therefore only be specified by callers that provide a unique cacheDir per scope (e.g. chunk labels in a weaved document).

showOutput

TRUE to printR CMD SHLIB output to the console.

verbose

TRUE to print detailed information about generated code to the console.

dryRun

TRUE to do a dry run (showing commands that would be used rather thanactually executing the commands).

windowsDebugDLL

TRUE to create a debug DLL on Windows (and ignored on other platforms).

echo

TRUE to silence output from optional R evaluation if set toFALSE.

Details

If thecode parameter is provided then thefile parameter is ignored.

Functions exported usingsourceCpp must meet several conditions,including being defined in the global namespace and having return typesthat are compatible withRcpp::wrap and parameter types that arecompatible withRcpp::as.See theRcpp::export documentation for more details.

Content of Rcpp Modules will be automatically loaded into the specifiedenvironment using theModule andpopulate functions.

If the source file has compilation dependencies on otherpackages (e.g.Matrix,RcppArmadillo) then anRcpp::depends attributeshould be provided naming these dependencies.

It's possible to embed chunks of R code within a C++ source file byincluding the R code within a block comment with theprefix of/*** R. For example:

/*** R# Call the fibonacci function defined in C++fibonacci(10)*/

Multiple R code chunks can be included in a C++ file. R code is sourced after the C++ compilation is completed so all functions and modules will be available to the R code.

Value

Returns (invisibly) a list with two elements:

functions Names of exported functions
modules Names of Rcpp modules

Note

ThesourceCpp function will not rebuild the shared library if the source file has not changed since the last compilation.

ThesourceCpp function is designed for compiling a standalone source file whose only dependencies are R packages. If you are compiling more than one source file or have external dependencies then you should create an R package rather than usingsourceCpp. Note that theRcpp::export attribute can also be used within packages via thecompileAttributes function.

If you are sourcing a C++ file from within thesrc directory of a package then the package'sLinkingTo dependencies,inst/include, andsrc directories are automatically included in the compilation.

If noRcpp::export attributes orRCPP_MODULE declarations are found within the source file then a warning is printed to the console. You can disable this warning by setting thercpp.warnNoExports option toFALSE.

See Also

Rcpp::export,Rcpp::depends,cppFunction,evalCpp

Examples

## Not run: sourceCpp("fibonacci.cpp")sourceCpp(code='  #include <Rcpp.h>  // [[Rcpp::export]]  int fibonacci(const int x) {    if (x == 0) return(0);    if (x == 1) return(1);    return (fibonacci(x - 1)) + fibonacci(x - 2);  }')## End(Not run)

[8]ページ先頭

©2009-2025 Movatter.jp