17 - FAQs
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(cpp4r)
Below are some Frequently Asked Questions about cpp4r. If you have a question that you think would fit well here please open an issue.
Is this only compatible with C++11?
No, cpp4r requires at least C++11. It is compatible with C++14, C++17, C++20, C++23 as well. The headers are written in a way that is compatible with all of these standards and newer features are used if the compiler supports them.
Can I specify which C++ standard to use?
Yes, you can specify the C++ standard to use when compiling your
cpp4r code. Some packages like tesseract use a
SystemRequirements field in their DESCRIPTION
file to specify the C++ standard because the underlying Tesseract
library requires it.
CRAN states that SystemRequirements: C++11 or any other
C++ standard must be written in the DESCRIPTION file if and
only if it is essential to build the package. Otherwise, it is not
necessary to specify the C++ standard.
My laptop uses C++NN but my cluster uses C++MM, how can I make sure my code works on both?
The headers were tested to verify that all the unit tests for cpp4r pass when compiled with C++11, C++14, C++17, C++20, and C++23.
For consistency, which is not required unless you have a dependency
that requires a specific C++ standard, you can write a
DESCRIPTION like this
Package: mypkg
Title: Descriptive Title
Version: 0.1.0
Authors@R:
person(
given = "You R.",
family = "Name",
role = c("aut", "cre")
)
Description: Descriptive description.
License: Apache License (>= 2)
Encoding: UTF-8
LinkingTo: cpp4r
SystemRequirements: C++11/14/17/20/23
and in Makevars.in (or Makevars.win) you can write
CXX_STD = CXX11/14/17/20/23
See the compiler optimization vignette for more details on how to set compiler flags and use anticonf scripts.
What are the underlying types of cpp4r objects?
| vector | element |
|---|---|
| cpp4r::integers | int |
| cpp4r::doubles | double |
| cpp4r::logicals | cpp4r::r_bool |
| cpp4r::strings | cpp4r::r_string |
| cpp4r::raws | uint8_t |
| cpp4r::list | SEXP |
How do I add elements to a list?
Use the push_back() method. You will need to use
cpp4r::as_sexp() if you want to convert arbitrary C++
objects to SEXP before inserting them into the list.
#include <cpp4r.hpp>
#include <vector>
[[cpp4r::register]]
cpp4r::writable::list foo_push() {
cpp4r::writable::list x;
// An object that is already a `SEXP`
x.push_back(R_NilValue);
// A single integer
x.push_back(cpp4r::as_sexp(1));
// A C++ vector of ints
std::vector<int> elt{1, 2, 3};
x.push_back(cpp4r::as_sexp(elt));
return x;
}
To create named lists, use the push_back() method with
the named literal syntax. The named literal syntax is defined in the
cpp4r::literals namespace. In this case, creating the named
literal automatically calls as_sexp() for you.
#include <cpp4r.hpp>
[[cpp4r::register]]
cpp4r::writable::list foo_push_named() {
using namespace cpp4r::literals;
cpp4r::writable::list x;
x.push_back({"foo"_nm = 1});
return x;
}
Note that if you know the size of the list ahead of time (which you often do!), then it is more efficient to state that up front.
#include <cpp4r.hpp>
#include <vector>
[[cpp4r::register]]
cpp4r::writable::list foo_push_sized() {
std::vector<int> elt{1, 2, 3};
R_xlen_t size = 3;
cpp4r::writable::list x(size);
x[0] = R_NilValue;
x[1] = cpp4r::as_sexp(1);
x[2] = cpp4r::as_sexp(elt);
return x;
}
Does cpp4r support default arguments?
cpp4r does not support default arguments, while convenient they would
require more complexity to support than is currently worthwhile. If you
need default argument support you can use a wrapper function around your
cpp4r registered function. A common convention is to name the internal
function with a trailing _.
#include <cpp4r.hpp>
[[cpp4r::register]]
double add_some_(double x, double amount) {
return x + amount;
}
add_some <- function(x, amount = 1) {
add_some_(x, amount)
}
add_some(1)
add_some(1, amount = 5)
How do I create a new empty list?
Define a new writable list object.
cpp4r::writable::list x;
How do I retrieve (named) elements from a named vector/list?
Use the [] accessor function.
x["foo"]
How can I tell whether a vector is named?
Use the named() method for vector classes.
#include <cpp4r.hpp>
[[cpp4r::register]]
bool is_named(cpp4r::strings x) {
return x.named();
}
is_named("foo")
is_named(c(x = "foo"))
How do I return a “cpp4r::writable::logicals” object with only a “FALSE” value?
You need to use list
initialization with {} to create the object.
#include <cpp4r.hpp>
[[cpp4r::register]]
cpp4r::writable::logicals my_false() {
return {FALSE};
}
[[cpp4r::register]]
cpp4r::writable::logicals my_true() {
return {TRUE};
}
[[cpp4r::register]]
cpp4r::writable::logicals my_both() {
return {TRUE, FALSE, TRUE};
}
my_false()
my_true()
my_both()
How do I create a new empty environment?
To do this you need to call the base::new.env() function
from C++. This can be done by creating a cpp4r::function
object and then calling it to generate the new environment.
#include <cpp4r.hpp>
[[cpp4r::register]]
cpp4r::environment create_environment() {
cpp4r::function new_env(cpp4r::package("base")["new.env"]);
return new_env();
}
How do I assign and retrieve values in an environment? What happens if I try to get a value that does not exist?
Use [] to retrieve or assign values from an environment
by name. If a value does not exist, it will error. To check for
existence ahead of time, use the exists() method.
#include <cpp4r.hpp>
[[cpp4r::register]]
bool foo_exists(cpp4r::environment x) {
return x.exists("foo");
}
[[cpp4r::register]]
void set_foo(cpp4r::environment x, double value) {
x["foo"] = value;
}
x <- new.env()
foo_exists(x)
set_foo(x, 1)
foo_exists(x)
How can I create a “cpp4r:raws” from a “std::string”?
There is no built in way to do this. One method would be to
push_back() each element of the string individually.
#include <cpp4r.hpp>
[[cpp4r::register]]
cpp4r::raws push_raws() {
std::string x("hi");
cpp4r::writable::raws out;
for (auto c : x) {
out.push_back(c);
}
return out;
}
push_raws()
How can I create a “std::string” from a “cpp4r::writable::string”?
Because C++ does not allow for two implicit cast, explicitly cast to
cpp4r::r_string first.
#include <cpp4r.hpp>
#include <string>
[[cpp4r::register]]
std::string my_string() {
cpp4r::writable::strings x({"foo", "bar"});
std::string elt = cpp4r::r_string(x[0]);
return elt;
}
What are the types for C++ iterators?
The iterators are ::iterator classes contained inside
the vector classes. For example the iterator for
cpp4r::doubles would be
cpp4r::doubles::iterator and the iterator for
cpp4r::writable::doubles would be
cpp4r::writable::doubles::iterator.
What’s wrong with “using namespace std”?
The using namespace std directive will not be included
in the generated code of the function signatures, and it will not be
included in future releases.
Please do not use using namespace std;. It is considered
bad practice in C++ because it can lead to name conflicts and
ambiguities, especially in larger codebases or when integrating multiple
libraries.
Some interesting discussion on this topic can be found in the following links:
- What’s the problem with “using namespace std;”?
- Why “using namespace std” is considered bad practice
- Why You Should Avoid Using namespace std in C++: Best Practices for Clean and Maintainable Code
Even when this will work:
#include <cpp4r.hpp>
#include <string>
using namespace std;
[[cpp4r::register]] std::string foobar() {
return string("foo") + "-bar";
}
Please please please do this instead:
#include <cpp4r.hpp>
#include <string>
[[cpp4r::register]]
std::string foobar() {
return std::string("foo") + "-bar";
}
How do I modify a vector in place?
In place modification breaks the normal semantics of R code. In
general it should be avoided, which is why cpp4r::writable
classes always copy their data when constructed.
However, if you are positive in-place modification is necessary for your use case, you can use the move constructor to do this.
#include <cpp4r.hpp>
[[cpp4r::register]]
void add_one(cpp4r::sexp x_sexp) {
cpp4r::writable::integers x(std::move(x_sexp.data()));
for (auto&& value : x) {
++value;
}
}
x <- c(1L, 2L, 3L, 4L)
.Internal(inspect(x))
add_one(x)
.Internal(inspect(x))
x
Should I call “unwind_protect” manually?
cpp4r::unwind_protect() is cpp4r’s way of safely calling
R’s C API. In short, it allows you to run a function that might throw an
R error, catch the longjmp() of that error, promote it to
an exception that is thrown and caught by a try/catch that cpp4r sets up
for you at .Call() time (which allows destructors to run),
and finally tells R to continue unwinding the stack now that the C++
objects have had a chance to destruct as needed.
Since cpp4r::unwind_protect() takes an arbitrary
function, you may be wondering if you should use it for your own custom
needs. In general, this is advised against because this is an extremely
advanced feature that is prone to subtle and hard to debug issues.
Destructors
The following setup for test_destructor_ok() with a
manual call to unwind_protect() would work:
#include <cpp4r.hpp>
class A {
public:
~A();
};
A::~A() {
Rprintf("hi from the destructor!");
}
[[cpp4r::register]]
void test_destructor_ok() {
A a{};
cpp4r::unwind_protect([&] {
Rf_error("oh no!");
});
}
[[cpp4r::register]]
void test_destructor_bad() {
cpp4r::unwind_protect([&] {
A a{};
Rf_error("oh no!");
});
}
test_destructor_ok()
But if you happen to move a into the
unwind_protect(), then it will not be destructed, and you
will end up with a memory leak at best, and a much more sinister issue
if your destructor is important:
test_destructor_bad()
#> Error: oh no!
In general, the only code that can be called within
unwind_protect() is “pure” C code or C++ code that only
uses POD (plain-old-data) types and no exceptions. If you mix complex
C++ objects with R’s C API within unwind_protect(), then
any R errors will result in a jump that prevents your destructors from
running.
Nested unwind_protect()
Another issue that can arise has to do with nested calls to
unwind_protect(). It is very hard (if not impossible) to
end up with invalidly nested unwind_protect() calls when
using the typical cpp4r API, but you can manually create a scenario like
the following:
#include <cpp4r.hpp>
[[cpp4r::register]]
void test_nested() {
cpp4r::unwind_protect([&] {
cpp4r::unwind_protect([&] {
Rf_error("oh no!");
});
});
}
If you were to run test_nested() from R, it would likely
crash or hang your R session due to the following chain of events:
test_nested()sets up a try/catch to catch unwind exceptions- The outer
unwind_protect()is called. It uses the C functionR_UnwindProtect()to call its lambda function. - The inner
unwind_protect()is called. It again usesR_UnwindProtect(), this time to callRf_error(). Rf_error()performs alongjmp()which is caught by the innerunwind_protect()and promoted to an exception.- That exception is thrown, but because the code is in the outer call
to
R_UnwindProtect()(a C function), it ends up throwing that exception across C stack frames. This is undefined behavior, which is known to have caused R to crash on certain platforms.
You might think that you’d never do this, but the same scenario can
also occur with a combination of 1 call to unwind_protect()
combined with usage of the cpp4r API:
#include <cpp4r.hpp>
[[cpp4r::register]]
void test_hidden_nested() {
cpp4r::unwind_protect([&] {
cpp4r::stop("oh no!");
});
}
Because cpp4r::stop() (and most of the cpp4r API) uses
unwind_protect() internally, this has indirectly ended up
in a nested unwind_protect() scenario again.
In general, if you must use unwind_protect() then you
must be very careful not to use any of the cpp4r API inside of the
unwind_protect() call.
It is worth pointing out that calling out to an R function from cpp4r
which then calls back into cpp4r is still safe, i.e. if the registered
version of the imaginary test_outer() function below was
called from R, then that would work:
#include <cpp4r.hpp>
[[cpp4r::register]]
void test_inner() {
cpp4r::stop("oh no!")
}
[[cpp4r::register]]
void test_outer() {
auto fn = cpp4r::package("mypackage")["test_inner"]
fn();
}
This might seem unsafe because cpp4r::package() uses
unwind_protect() to call the R function for
test_inner(), which then goes back into C++ to call
cpp4r::stop(), which itself uses
unwind_protect(), so it seems like the code is in a nested
scenario, but this scenario does actually work. It makes more sense if
you analyze it one step at a time:
- Call the R function for
test_outer() - A try/catch is set up to catch unwind exceptions
- The C++ function for
test_outer()is called cpp4r::package()usesunwind_protect()to call the R function fortest_inner()- Call the R function for
test_inner() - A try/catch is set up to catch unwind exceptions (this is the key!)
- The C++ function for
test_inner()is called cpp4r::stop("oh no!")is called, which usesunwind_protect()to callRf_error(), causing alongjmp(), which is caught by thatunwind_protect()and promoted to an exception.- That exception is thrown, but this time it is caught by the
try/catch set up by
test_inner()as it was entered from the R side. This prevents that exception from crossing the C++ -> C boundary. - The try/catch calls
R_ContinueUnwind(), whichlongjmp()s again, and now theunwind_protect()set up bycpp4r::package()catches that, and promotes it to an exception. - That exception is thrown and caught by the try/catch set up by
test_outer(). - The try/catch calls
R_ContinueUnwind(), whichlongjmp()s again, and at this point thelongjmp()can safely proceed to force an R error.
If you have read the above bullet and still feel like you need to
call unwind_protect(), then you should keep in mind the
following when writing the function to unwind-protect:
- You should not create any C++ objects that have destructors.
- You should not use any parts of the cpp4r API that may call
unwind_protect(). - You must be very careful not to call
unwind_protect()in a nested manner.
In other words, if you only use plain-old-data types, are careful to
never throw exceptions, and only use R’s C API, then you can use
unwind_protect().
One place you may want to do this is when working with long character
vectors. Unfortunately, due to the way cpp4r must protect the individual
CHARSXP objects that make up a character vector, it can currently be
quite slow to use the cpp4r API for this. Consider this example of
extracting out individual elements with x[i] vs using the
native R API:
#include <cpp4r.hpp>
[[cpp4r::register]]
cpp4r::sexp test_extract_cpp4r(cpp4r::strings x) {
const R_xlen_t size = x.size();
for (R_xlen_t i = 0; i < size; ++i) {
(void) x[i];
}
return R_NilValue;
}
[[cpp4r::register]]
cpp4r::sexp test_extract_r_api(cpp4r::strings x) {
const R_xlen_t size = x.size();
const SEXP data{x};
cpp4r::unwind_protect([&] {
for (R_xlen_t i = 0; i < size; ++i) {
(void) STRING_ELT(data, i);
}
});
return R_NilValue;
}
set.seed(123)
x <- sample(letters, 1e6, replace = TRUE)
bench::mark(
test_extract_cpp4r(x),
test_extract_r_api(x)
)
There are plans to improve on this in the future, but for now this is
one of the only places where it is felt to be reasonable to call
unwind_protect() manually.
How do I modify a matrix rownames/colnames on C++ side?
Any of the following options will work (the commented code works with cpp4r):
[[cpp4r::register]]
cpp4r::doubles_matrix<> copy_mat(cpp4r::doubles_matrix<> x) {
cpp4r::writable::doubles_matrix<> out = x;
// SEXP dimnames = x.attr("dimnames");
// if (dimnames != R_NilValue) {
// Rf_setAttrib(out.data(), R_DimNamesSymbol, dimnames);
// }
out.attr("dimnames") = x.attr("dimnames");
return out;
}
[[cpp4r::register]]
SEXP copy_mat_as_sexp(cpp4r::doubles_matrix<> x) {
cpp4r::writable::doubles_matrix<> out = x;
// SEXP dimnames = x.attr("dimnames");
// if (dimnames != R_NilValue) {
// Rf_setAttrib(out.data(), R_DimNamesSymbol, dimnames);
// }
out.attr("dimnames") = x.attr("dimnames");
return out;
}
[[cpp4r::register]]
cpp4r::doubles_matrix<> create_mat() {
cpp4r::writable::doubles_matrix<> out(2, 2);
out(0, 0) = 1;
out(0, 1) = 2;
out(1, 0) = 3;
out(1, 1) = 4;
cpp4r::writable::list dimnames(2);
dimnames[0] = cpp4r::strings({"a", "b"});
dimnames[1] = cpp4r::strings({"c", "d"});
out.attr("dimnames") = dimnames;
return out;
}
[[cpp4r::register]]
cpp4r::doubles_matrix<> create_mat_no_rownames() {
cpp4r::writable::doubles_matrix<> out(2, 2);
out(0, 0) = 1;
out(0, 1) = 2;
out(1, 0) = 3;
out(1, 1) = 4;
cpp4r::writable::list dimnames(2);
dimnames[0] = R_NilValue; // No row names
dimnames[1] = cpp4r::strings({"x1", "x2"});
out.attr("dimnames") = dimnames;
return out;
}
How do I use the same seed defined in R for random number generation in C++?
If you use set.seed(42) (or any other value) in R, you
need to explicitly use GetRNGstate() and
PutRNGstate() in your C++ code to synchronize the RNG state
between R and C++. Otherwise, the result will not be replicable for not
correctly using the Random Number Generator (RNG) state from R.
#include "cpp4r/doubles.hpp"
#include "R.h"
#include "Rmath.h"
// single draw from standard normal using R's RNG (replicable result)
[[cpp4r::register]] double using_rng_() {
GetRNGstate();
double x = Rf_rnorm(0, 1);
PutRNGstate();
return x;
}