6.11 Connections, External Pointers, and Finalizers

R RUNTIMESTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18

6.11.1 Motivation

R values are normally self-contained. A vector holds data inside the SEXP. An environment holds name-value bindings. An R object is a tree of SEXPs. But some R objects represent things outside R: an open file, a network connection, a handle to a C data structure.

An external pointer is an R object, of type EXTPTRSXP, that holds a C address plus two R values, a tag and a protected value. The address usually points to a C library’s handle or to a struct the package allocated. R never duplicates an external pointer: copying an object that contains one copies the reference, and the pointer object stays shared. When one is serialized, the address is not written, and it reads back as NULL, so the pointer cannot move between processes.

An external pointer can carry a finalizer, R or C code that R runs after the garbage collector finds the pointer unreachable. It typically frees the C memory or closes the handle.

External pointers break many assumptions about R values. They are why a database handle or a C library object cannot be sent to a worker the way a vector can.

6.11.2 Mental model

An ordinary R value is pure data. A numeric vector contains numbers. The numbers can be copied, moved, serialized, or passed to another process. The value is the same wherever it goes.

An external pointer is a reference to a resource. The resource is external to R. It is usually stateful. A file pointer refers to a specific open file. The file has a position, a buffer state, permissions. Copying the pointer does not copy the file. Both copies refer to the same file. Writing to one affects the other.

# Ordinary value: pure data.
x <- c(1, 2, 3)

# A connection: a handle to a resource.
f <- file("data.csv", "r")
# f is an integer index into R's connection table, with class
# c("file", "connection") and a "conn_id" attribute that is an
# external pointer.

The file is a shared resource managed by the operating system. R cannot own it completely. The file can be accessed by other parts of the program or by other processes. The R value is only a handle.

6.11.3 Mechanism

Creating external pointers

User code does not usually create external pointers directly. Instead, packages do it from C, with R_MakeExternalPtr(void *p, SEXP tag, SEXP prot). This creates a SEXP of type EXTPTRSXP. The pointer field holds the C address. By convention the tag identifies what the pointer points at, and prot keeps alive any R object the C memory depends on.

SEXP result = R_MakeExternalPtr((void *)file_handle, R_NilValue, R_NilValue);
return result;

The resulting SEXP is returned to user code. As long as it is reachable, the collector keeps it, and the file stays open.

Finalizers

A finalizer cleans up the resource. It can be an R function, registered with R_RegisterFinalizer or reg.finalizer() from R, or a C function, registered with R_RegisterCFinalizer. The Ex variants take a third argument, onexit, that asks R to run the finalizer at the end of the session too, since R does not collect garbage when it shuts down.

void finalizer_close_file(SEXP ptr) {
  FILE *f = (FILE *)R_ExternalPtrAddr(ptr);
  if (f != NULL) {
    fclose(f);
    R_ClearExternalPtr(ptr);
  }
}

// Register the finalizer.
R_RegisterCFinalizerEx(result, finalizer_close_file, TRUE);

When the external pointer becomes unreachable, the next collection marks its finalizer ready to run, and R calls finalizer_close_file soon after. Clearing the pointer afterwards, as Writing R Extensions advises, keeps a stale address from being used again.

The collector does not run finalizers itself. It marks them, and the evaluator runs pending finalizers at a safe point: every thousand or so evaluations, and at the end of an explicit gc(). They run on the one R thread, so a slow finalizer blocks the whole R process.

Connections

Connections are not an external pointer type of their own; R has no CONNSXP. A connection is an integer vector, the index of a slot in R’s C-level connection table (Connections in connections.c), with a class such as c("file", "connection") and a conn_id attribute that is an external pointer. The connection itself, a C struct with its buffers and file position, lives in the table. It can be a file, a pipe, a socket, or a compressed file.

A connection has state: position, buffering mode, encoding, permissions. Operations like read, write, and close modify this state. The connection code takes no locks, so only one thread may use a connection.

6.11.4 Internal mechanics

The copy problem

R does not copy external pointers.

f <- file("data.csv", "r")
g <- f
# g and f are bound to the same R object:
# one connection, one file state.

g <- f copies nothing, not even the SEXP: both names bind to the same object. An explicit duplicate() would not help either, because duplicate() returns an external pointer unchanged. Closing g closes the file for every name.

Copy-on-modify therefore never reaches the resource. If the connection’s integer vector is modified, R copies the vector and its attributes, and the copy carries the same conn_id pointer, so both copies still name the same open file.

R never duplicates an external pointer, so copy-on-modify does not apply to it. Every reference to it reaches the same resource.

The serialization problem

External pointers do not survive serialization. When R saves an object, it writes the data out, and reading it back reconstructs the object. For an external pointer, R writes the tag and the protected value but not the address, and on reading it sets the address to NULL (serialize.c).

An address means nothing outside the process that made it. In a new session the memory it named is gone or holds something else. A package has to check for a NULL address before using a restored pointer, or rebuild the resource from information it keeps elsewhere.

The address of an external pointer is not serialized. A restored pointer has a NULL address, so the pointer has meaning only within the process that created it.

Fork and copy-on-write failure

Fork creates a child process with a copy of the parent’s memory. External pointers are inherited by the child. But the resources they refer to are often not duplicated.

If the parent has an open file, the child inherits a copy of the file descriptor. POSIX specifies that the copy refers to the same open file description, so parent and child share one file offset, and a read in one moves the position the other reads from. A C library’s buffer (behind a FILE *) is copied with the rest of memory, so each side also holds its own copy of whatever was buffered.

A database connection is a socket plus the client library’s state about it. After fork, parent and child hold the same socket and two copies of that state, and both can talk to the server on what the server sees as one session. PostgreSQL’s libpq documentation warns against using a connection across fork for this reason.

f <- file("data.csv", "r")
pid <- parallel::mcfork()
# In the child, f still points to the same file descriptor.
# Both parent and child can read/write the same file.
# Their operations interfere.

When a process forks, external pointers are inherited by the child. The child and parent share references to the same external resources.

6.11.5 Concurrency implications

An external pointer adds no synchronization of its own, and neither does the C library behind it, unless that library says so.

Suppose two interpreters (or threads) both hold references to an external pointer to an open file, and both call file operations on it at the same time. The read position moves under each of them, buffered data can be read twice or lost, and the library’s own state can be corrupted.

An external pointer carries no lock, so sharing one between threads is safe only when the resource behind it is. Most C resources held through external pointers are not safe to use from two threads at once.

The apartment model prevents this by isolation. Each interpreter owns its external pointers. No external pointer is shared between interpreters. If an interpreter closes a file, only that interpreter is affected.

If a worker needs to use a file, it must open it independently. The worker does not inherit the parent’s file handle. This is safe but means each worker duplicates resources.

threaded-r isolates external pointers per-interpreter. An external pointer lives in one interpreter’s heap, and values cross between interpreters as serialized bytes, so a pointer that crosses arrives with a NULL address.

6.11.6 Connections and threading

R’s connections, the objects behind file(), url() and socketConnection(), have no locks of their own. Connections are not thread-safe.

If two threads write to the same connection, their writes can interleave and the file ends up with garbled records.

If one thread reads from a connection while another thread is writing, the read position is inconsistent.

Connections are meant for single-threaded use. In multithreaded R, each thread must use its own connection.

# Safe: each worker opens its own connection.
f <- file("data.csv", "r")
# The connection f is private to this interpreter.

6.11.7 External pointers in threaded-r

threaded-r inherits GNU R’s external pointer implementation. Garbage collection is per-interpreter, so a finalizer runs in the interpreter whose heap the object lived in. When an interpreter is destroyed, it runs the finalizers registered to run at exit (R_RunExitFinalizers), as GNU R does at the end of a session.

The connection table is the exception to per-interpreter state: it stays process-wide, as in GNU R. threaded-r adds a lock around claiming and freeing a slot and records which interpreter owns each one, and getConnection refuses a slot that belongs to another interpreter. Only stdin, stdout and stderr are shared.

Sharing external pointers between interpreters is not supported. If a worker needs to use a file, it opens the file directly. The worker does not inherit the parent’s connection.

6.11.8 External pointers in r-in-rust

rrs implements R’s EXTPTRSXP, because compiled packages create external pointers through the C API and expect them to behave as in GNU R. The heap stores the address as a plain integer (usize) next to the tag and protected value, so the heap crate holds no raw pointers and stays in safe Rust; what the address means is the FFI layer’s business (crates/rrs-runtime/src/obj.rs).

Finalizers follow R’s rule. An object with a pending finalizer survives the collection that finds it unreachable, its finalizer runs at a safe point afterwards, and the object dies at the next collection. Each interpreter owns its heap, so an external pointer belongs to one interpreter, as in threaded-r.

6.11.9 The hard part

External pointers and finalizers are necessary for integration with C libraries. But they create problems for parallelism.

The core issue is that resources are usually not duplicable or shareable. A file descriptor is a reference to kernel state. A database connection is a session with a server. Copying a file descriptor gives a second number for the same open file, not an independent resource, and a database session cannot be copied at all. Neither can be shared between threads without coordination. They must be carefully managed.

In single-threaded R, the garbage collector handles this. When an external pointer is no longer referenced, the finalizer runs and the resource is released.

In multithreaded R, the problem becomes: who owns the resource? If two threads hold references to the same file, who closes it? If one thread closes it, the other thread’s operations fail. If neither thread closes it, the file leaks.

The apartment model solves this by ownership: each resource is owned by one interpreter. But this means sharing resources requires explicit synchronization. Workers cannot inherit files from the parent and assume they still work. They must coordinate somehow.

6.11.10 Open questions

Does the runtime convert external pointers to owned values automatically when sent from one interpreter to another? For example, converting a file handle to a path string and re-opening the file in the target interpreter?

Can external pointers be protected by locks? If a lock guards each external pointer, multiple threads can access it serially. This is slow but correct.

Further reading

Writing R Extensions, Section 5.13, “External pointers and weak references”: https://cran.r-project.org/doc/manuals/r-release/R-exts.html#External-pointers-and-weak-references

R Internals, Section 1.1.3, “The ‘data’”, on the layout of EXTPTRSXP and WEAKREFSXP: https://cran.r-project.org/doc/manuals/r-release/R-ints.html#The-_0027data_0027

POSIX, fork(), on the file descriptors a child inherits: https://pubs.opengroup.org/onlinepubs/9799919799/functions/fork.html

PostgreSQL documentation, “Database Connection Control Functions”, the libpq warning about fork: https://www.postgresql.org/docs/current/libpq-connect.html

Where this appears

  • threaded-r An external pointer’s address is valid in every thread of the process, but the resource behind it is rarely safe to use from two at once.
  • r-in-rust (rrs) rrs implements R’s external pointer type, because compiled packages create external pointers through the C API.

Where to go next

Back to top