README.md
1
2<!-- README.md is generated from README.Rmd. Please edit that file -->
3bindrcpp
4========
5
6[![Travis-CI Build Status](https://travis-ci.org/krlmlr/bindrcpp.svg?branch=master)](https://travis-ci.org/krlmlr/bindrcpp) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/krlmlr/bindrcpp?branch=master&svg=true)](https://ci.appveyor.com/project/krlmlr/bindrcpp) [![CRAN\_Status\_Badge](http://www.r-pkg.org/badges/version/bindrcpp)](https://cran.r-project.org/package=bindrcpp)
7
8It's easy to create active bindings in R via [`makeActiveBinding()`](https://www.rdocumentation.org/packages/base/versions/3.3.1/topics/bindenv). This package faciliates the creation of active bindings that link back to C++ code. It provides an interface that allows binding several identifiers in an environment to the same C++ function, which is then called with the name (and a payload) as argument.
9
10It is recommended to use the newer `_wrapped` functions that support passing an arbitrary `Rcpp::List` as payload. This allows to store an `Rcpp::XPtr` to a C++ object in that list. The `XPtr` then will be released when the payload is garbage-collected, and the C++ object will be destroyed.
11
12Installation
13------------
14
15You can install bindrcpp from github with:
16
17``` r
18# install.packages("devtools")
19devtools::install_github("krlmlr/bindrcpp")
20```
21
22Example
23-------
24
25The following C++ module exports a function `test_tolower_bindings()` that creates active bindings that return the binding name in lowercase.
26
27``` cpp
28#include <Rcpp.h>
29
30// [[Rcpp::depends(bindrcpp)]]
31#include <bindrcpp.h>
32
33#include <algorithm>
34#include <string>
35
36using namespace Rcpp;
37
38using namespace bindrcpp;
39
40SEXP tolower_callback(const String& name, PAYLOAD) {
41 std::string name_string = name;
42 std::transform(name_string.begin(), name_string.end(), name_string.begin(), ::tolower);
43 return CharacterVector(name_string);
44}
45
46// [[Rcpp::export]]
47SEXP test_tolower_bindings(CharacterVector names, Environment parent) {
48 // We don't pass any payload here
49 return bindrcpp::create_env_string(
50 names, &tolower_callback, PAYLOAD(NULL), parent);
51}
52```
53
54This function can be called from R:
55
56``` r
57env <- test_tolower_bindings(c("Converting", "to", "LOWERCASE"), .GlobalEnv)
58ls(env)
59#> [1] "Converting" "LOWERCASE" "to"
60env$Converting
61#> [1] "converting"
62env$to
63#> [1] "to"
64env$LOWERCASE
65#> [1] "lowercase"
66env$y
67#> NULL
68```
69
70The bindings are read-only:
71
72``` r
73env$Converting <- "CONVERTING"
74#> Error: Binding is read-only.
75```
76