technical-C-structs-in-R.Rmd
structs
in C are a data structure for combining items which may be of different types.
In Cairo, a common struct contains the data defining a single rectangle.
typedef struct _cairo_rectangle {
double x,
double y,
double width,
double height;
} cairo_rectangle_t;
Elements of a struct may be accessed by name using ->
or .
depending on whether it is a pointer or not
void some_function(cairo_rectangle_t *my_rect) {
printf("My rectangle width is %f\n", my_rect->width);
}
structs
in R are implemented as external pointer objects:
In this next example, a rectangle struct is created in R. Note:
my_rect <- cairo_rectangle_t(x = 10, y = 10, width = 100, height = 200) my_rect
#> <pointer: 0x7fea5f893310>
#> attr(,"class")
#> [1] "cairo_rectangle_t"
typeof(my_rect)
#> [1] "externalptr"
class(my_rect)
#> [1] "cairo_rectangle_t"
as.list()
For some structs, the as.list()
method has been implemented on the class to convert the external pointer to a regular R list.
Note: This is not currently a link between the external pointer data and the list representation. Changing one of the objects doesn’t not change the other one.
as.list(my_rect)
#> $x
#> [1] 10
#>
#> $y
#> [1] 10
#>
#> $width
#> [1] 100
#>
#> $height
#> [1] 200