---
title: "12 - External Pointers"
output:
  litedown::html_format:
    options:
      toc: true
      number_sections: true
vignette: >
  %\VignetteIndexEntry{12 - External Pointers}
  %\VignetteEngine{litedown::vignette}
  %\VignetteEncoding{UTF-8}
editor:
  markdown:
    wrap: sentence
bibliography: ["references.bib"]
---

In `cpp4r`, you can use `external_pointer`. In `Rcpp`, you can use `XPtr` to create external pointers. These have significantly different syntax, and `cpp4r` does not provide an `attr` method for external pointers.

For example, the [cpp11tesseract](https://github.com/pachadotdev/cpp11tesseract) package defines:

```cpp
typedef cpp4r::external_pointer<tesseract::TessBaseAPI, tess_finalizer> TessPtr;
```

You can then call `TessPtr` with:

```cpp
TessPtr ptr(api);
return ptr;
```

As a result, the R equivalent that the OCR C++ function verifies that the engine is such that the following is true:

```r
stopifnot(inherits(engine, "externalptr"))
```

The equivalent [tesseract](https://github.com/ropensci/tesseract/) package, which uses `Rcpp`, defines:

```
typedef Rcpp::XPtr<tesseract::TessBaseAPI, Rcpp::PreserveStorage, tess_finalizer, true> TessPtr;
```

You can then call `TessPtr` with:

```cpp
TessPtr ptr(api);
ptr.attr("class") = Rcpp::CharacterVector::create("tesseract");
return ptr;
```

Similarly, the `Rcpp` version checks the engine with:

```r
stopifnot(inherits(engine, "tesseract"))
```
