Intended to answer common questions about the usage of cpp11 objects
#include <cpp11.hpp>
using namespace cpp11;
[[cpp11::register]]
::list fn() {
cpp11::writable::list x;
cpp11.push_back({"foo"_nm = 1});
xreturn x;
}
auto
keyword with R’s new.env
to return a new empty environment. This should then be passed to cpp11::environment
before use#include <cpp11.hpp>
using namespace cpp11;
[[cpp11::register]]
::environment get_environment() {
cpp11auto new_env = cpp11::package("base")["new.env"];
::environment my_env(new_env());
cpp11return my_env;
}
my_env["bar"] == R_UnboundValue
which returns TRUE
if the value is unassigned and NULL.#include <cpp11.hpp>
using namespace cpp11;
[[cpp11::register]]
::r_bool foo_exists(){
cpp11auto new_env = cpp11::package("base")["new.env"];
::environment my_env(new_env());
cpp11
["foo"] = 5;
my_env::r_bool fofo = (as_cpp<int>(my_env["foo"]) == 5);
cpp11
return (fofo);
}
#include <cpp11.hpp>
using namespace cpp11;
[[cpp11::register]]
::r_bool bar_exists(){
cpp11auto new_env = cpp11::package("base")["new.env"];
::environment my_env(new_env());
cpp11
::r_bool barbar = (my_env["bar"] == R_UnboundValue);
cpp11
return (!barbar);
}
cpp11:raws
from a std::string
?#include <cpp11.hpp>
using namespace cpp11;
[[cpp11::register]]
::raws push() {
cpp11
std::string x("hi");
::writable::raws out;
cpp11
for (auto c : x) {
.push_back(c);
out}
return out;
}
vector | element |
---|---|
integers | int |
doubles | double |
logical | r_bool |
strings | r_string |
raws | uint8_t |
list | SEXP |
cpp11::writable::list x;
x["foo"]
TODO
cpp11::doubles::iterator
#include <cpp11.hpp>
using namespace cpp11;
[[cpp11::register]]
::writable::logicals fn2() {
cpp11return {false};
}
#include <cpp11.hpp>
using namespace cpp11;
[[cpp11::register]]
::writable::logicals fn() {
cpp11return false;
}
#include <cpp11.hpp>
[[cpp11::register]]
std::string fn(bool length) {
if(length) {
return ("length");
}
return ("width");
}
<- function(length = FALSE) {
full_fn fn(length)
}full_fn(TRUE)
#> [1] "length"
#> "length"
full_fn()
#> [1] "width"
#> "width"
using namespace
in my code as well as std::
inside of [[cpp11::register]]
functions?[[cpp11::register]]
need to be fully qualified. However type names within those functions will work as expected.The following won’t compile
#include <cpp11.hpp>
#include <string>
using namespace std;
[[cpp11::register]]
() {
string foobarreturn string("foo") + "-bar";
}
But this will compile and work as expected
#include <cpp11.hpp>
#include <string>
using namespace std;
[[cpp11::register]]
std::string foobar() {
return string("foo") + "-bar";
}
writable::
will always make a copy, but it has a move constructor, so you can use cpp11::writable::integers(std::move(x))
and it won’t make a copy of the data.